How do you determine a processing time in Python?

前端 未结 9 1560
天涯浪人
天涯浪人 2020-12-09 14:27

I\'m new to Python, and confused by the date/time documentation. I want to compute the time that it takes to perform a computation.

In java, I would write:

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 15:12

    I also got a requirement to calculate the process time of some code lines. So I tried the approved answer and I got this warning.

    DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead
    

    So python will remove time.clock() from Python 3.8. You can see more about it from issue #13270. This warning suggest two function instead of time.clock(). In the documentation also mention about this warning in-detail in time.clock() section.

    Deprecated since version 3.3, will be removed in version 3.8: The behaviour of this function depends on the platform: use perf_counter() or process_time() instead, depending on your requirements, to have a well defined behaviour.

    Let's look at in-detail both functions.


    • time.perf_counter()

    Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

    New in version 3.3.

    So if you want it as nanoseconds, you can use time.perf_counter_ns() and if your code consist with time.sleep(secs), it will also count. Ex:-

    import time
    
    
    def func(x):
        time.sleep(5)
        return x * x
    
    
    lst = [1, 2, 3]
    tic = time.perf_counter()
    print([func(x) for x in lst])
    toc = time.perf_counter()
    print(toc - tic)
    
    # [1, 4, 9]
    # 15.0041916 --> output including 5 seconds sleep time
    

    • time.process_time()

    Return the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep. It is process-wide by definition. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

    New in version 3.3.

    So if you want it as nanoseconds, you can use time.process_time_ns() and if your code consist with time.sleep(secs), it won't count. Ex:-

    import time
    
    
    def func(x):
        time.sleep(5)
        return x * x
    
    
    lst = [1, 2, 3]
    tic = time.process_time()
    print([func(x) for x in lst])
    toc = time.process_time()
    print(toc - tic)
    
    # [1, 4, 9]
    # 0.0 --> output excluding 5 seconds sleep time
    

    Please note both time.perf_counter_ns() and time.process_time_ns() come up with Python 3.7 onward.

提交回复
热议问题