How do you determine a processing time in Python?

前端 未结 9 1558
天涯浪人
天涯浪人 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 14:54

    You can implement two tic() and tac() functions, where tic() captures the time which it is called, and tac() prints the time difference since tic() was called. Here is a short implementation:

    import time
    
    _start_time = time.time()
    
    def tic():
        global _start_time 
        _start_time = time.time()
    
    def tac():
        t_sec = round(time.time() - _start_time)
        (t_min, t_sec) = divmod(t_sec,60)
        (t_hour,t_min) = divmod(t_min,60) 
        print('Time passed: {}hour:{}min:{}sec'.format(t_hour,t_min,t_sec))
    

    Now in your code you can use it as:

    tic()
    do_some_stuff()
    tac()
    

    and it will, for example, output:

    Time passed: 0hour:7min:26sec
    

    See also:

    • Python's datetime library: https://docs.python.org/2/library/datetime.html
    • Python's time library: https://docs.python.org/2/library/time.html

提交回复
热议问题