How do you determine a processing time in Python?

前端 未结 9 1512
天涯浪人
天涯浪人 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:13
    python -m timeit -h
    
    0 讨论(0)
  • 2020-12-09 15:15

    Building on and updating a number of earlier responses (thanks: SilentGhost, nosklo, Ramkumar) a simple portable timer would use timeit's default_timer():

    >>> import timeit
    >>> tic=timeit.default_timer()
    >>> # Do Stuff
    >>> toc=timeit.default_timer()
    >>> toc - tic #elapsed time in seconds
    

    This will return the elapsed wall clock (real) time, not CPU time. And as described in the timeit documentation chooses the most precise available real-world timer depending on the platform.

    ALso, beginning with Python 3.3 this same functionality is available with the time.perf_counter performance counter. Under 3.3+ timeit.default_timer() refers to this new counter.

    For more precise/complex performance calculations, timeit includes more sophisticated calls for automatically timing small code snippets including averaging run time over a defined set of repetitions.

    0 讨论(0)
  • 2020-12-09 15:16

    For Python 3.3 and later time.process_time() is very nice:

    import time
    
    t = time.process_time()
    #do some stuff
    elapsed_time = time.process_time() - t
    
    0 讨论(0)
提交回复
热议问题