Get time of execution of a block of code in Python 2.7

后端 未结 6 712
北荒
北荒 2020-12-07 08:52

I would like to measure the time elapsed to evaluate a block of code in a Python program, possibly separating between user cpu time, system cpu time and elapsed time.

<
6条回答
  •  半阙折子戏
    2020-12-07 09:19

    I found myself solving this problem again and again, so I finally created a library for it. Install with pip install timer_cm. Then:

    from time import sleep
    from timer_cm import Timer
    
    with Timer('Long task') as timer:
        with timer.child('First step'):
            sleep(1)
        for _ in range(5):
            with timer.child('Baby steps'):
                sleep(.5)
    

    Output:

    Long task: 3.520s
      Baby steps: 2.518s (71%)
      First step: 1.001s (28%)
    

提交回复
热议问题