How to measure time taken between lines of code in python?

前端 未结 7 920
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 11:00

So in Java, we can do How to measure time taken by a function to execute

But how is it done in python? To measure the time start and end time between lines of codes?

7条回答
  •  误落风尘
    2020-12-04 11:43

    If you want to measure CPU time, can use time.process_time() for Python 3.3 and above:

    import time
    start = time.process_time()
    # your code here    
    print(time.process_time() - start)
    

    First call turns the timer on, and second call tells you how many seconds have elapsed.

    There is also a function time.clock(), but it is deprecated since Python 3.3 and will be removed in Python 3.8.

    There are better profiling tools like timeit and profile, however time.process_time() will measure the CPU time and this is what you're are asking about.

    If you want to measure wall clock time instead, use time.time().

提交回复
热议问题