How do I get time of a Python program's execution?

后端 未结 30 1637
甜味超标
甜味超标 2020-11-22 02:20

I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.

I\'ve looked at the timeit

相关标签:
30条回答
  • 2020-11-22 02:54

    I tried and found time difference using the following scripts.

    import time
    
    start_time = time.perf_counter()
    [main code here]
    print (time.perf_counter() - start_time, "seconds")
    
    0 讨论(0)
  • 2020-11-22 02:55

    I really like Paul McGuire's answer, but I use Python 3. So for those who are interested: here's a modification of his answer that works with Python 3 on *nix (I imagine, under Windows, that clock() should be used instead of time()):

    #python3
    import atexit
    from time import time, strftime, localtime
    from datetime import timedelta
    
    def secondsToStr(elapsed=None):
        if elapsed is None:
            return strftime("%Y-%m-%d %H:%M:%S", localtime())
        else:
            return str(timedelta(seconds=elapsed))
    
    def log(s, elapsed=None):
        line = "="*40
        print(line)
        print(secondsToStr(), '-', s)
        if elapsed:
            print("Elapsed time:", elapsed)
        print(line)
        print()
    
    def endlog():
        end = time()
        elapsed = end-start
        log("End Program", secondsToStr(elapsed))
    
    start = time()
    atexit.register(endlog)
    log("Start Program")
    

    If you find this useful, you should still up-vote his answer instead of this one, as he did most of the work ;).

    0 讨论(0)
  • 2020-11-22 02:55

    In IPython, "timeit" any script:

    def foo():
        %run bar.py
    timeit foo()
    
    0 讨论(0)
  • 2020-11-22 02:56

    I was having the same problem in many places, so I created a convenience package horology. You can install it with pip install horology and then do it in the elegant way:

    from horology import Timing
    
    with Timing(name='Important calculations: '):
        prepare()
        do_your_stuff()
        finish_sth()
    

    will output:

    Important calculations: 12.43 ms
    

    Or even simpler (if you have one function):

    from horology import timed
    
    @timed
    def main():
        ...
    

    will output:

    main: 7.12 h
    

    It takes care of units and rounding. It works with python 3.6 or newer.

    0 讨论(0)
  • 2020-11-22 02:57

    Similar to the response from @rogeriopvl I added a slight modification to convert to hour minute seconds using the same library for long running jobs.

    import time
    start_time = time.time()
    main()
    seconds = time.time() - start_time
    print('Time Taken:', time.strftime("%H:%M:%S",time.gmtime(seconds)))
    

    Sample Output

    Time Taken: 00:00:08
    
    0 讨论(0)
  • 2020-11-22 02:57

    The time of a Python program's execution measure could be inconsistent depending on:

    • Same program can be evaluated using different algorithms
    • Running time varies between algorithms
    • Running time varies between implementations
    • Running time varies between computers
    • Running time is not predictable based on small inputs

    This is because the most effective way is using the "Order of Growth" and learn the Big "O" notation to do it properly.

    Anyway, you can try to evaluate the performance of any Python program in specific machine counting steps per second using this simple algorithm: adapt this to the program you want to evaluate

    import time
    
    now = time.time()
    future = now + 10
    step = 4 # Why 4 steps? Because until here already four operations executed
    while time.time() < future:
        step += 3 # Why 3 again? Because a while loop executes one comparison and one plus equal statement
    step += 4 # Why 3 more? Because one comparison starting while when time is over plus the final assignment of step + 1 and print statement
    print(str(int(step / 10)) + " steps per second")
    
    0 讨论(0)
提交回复
热议问题