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

前端 未结 7 919
伪装坚强ぢ
伪装坚强ぢ 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:50

    Putting the code in a function, then using a decorator for timing is another option. (Source) The advantage of this method is that you define timer once and use it with a simple additional line for every function.

    First, define timer decorator:

    import functools
    import time
    
    def timer(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            start_time = time.perf_counter()
            value = func(*args, **kwargs)
            end_time = time.perf_counter()
            run_time = end_time - start_time
            print("Finished {} in {} secs".format(repr(func.__name__), round(run_time, 3)))
            return value
    
        return wrapper
    

    Then, use the decorator while defining the function:

    @timer
    def doubled_and_add(num):
        res = sum([i*2 for i in range(num)])
        print("Result : {}".format(res))
    

    Let's try:

    doubled_and_add(100000)
    doubled_and_add(1000000)
    

    Output:

    Result : 9999900000
    Finished 'doubled_and_add' in 0.0119 secs
    Result : 999999000000
    Finished 'doubled_and_add' in 0.0897 secs
    

    Note: I'm not sure why to use time.perf_counter instead of time.time. Comments are welcome.

提交回复
热议问题