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

后端 未结 30 2338
甜味超标
甜味超标 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:47

    If you want to measure time in microseconds, then you can use the following version, based completely on the answers of Paul McGuire and Nicojo - it's Python 3 code. I've also added some colour to it:

    import atexit
    from time import time
    from datetime import timedelta, datetime
    
    
    def seconds_to_str(elapsed=None):
        if elapsed is None:
            return datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
        else:
            return str(timedelta(seconds=elapsed))
    
    
    def log(txt, elapsed=None):
        colour_cyan = '\033[36m'
        colour_reset = '\033[0;0;39m'
        colour_red = '\033[31m'
        print('\n ' + colour_cyan + '  [TIMING]> [' + seconds_to_str() + '] ----> ' + txt + '\n' + colour_reset)
        if elapsed:
            print("\n " + colour_red + " [TIMING]> Elapsed time ==> " + elapsed + "\n" + colour_reset)
    
    
    def end_log():
        end = time()
        elapsed = end-start
        log("End Program", seconds_to_str(elapsed))
    
    
    start = time()
    atexit.register(end_log)
    log("Start Program")
    

    log() => function that prints out the timing information.

    txt ==> first argument to log, and its string to mark timing.

    atexit ==> Python module to register functions that you can call when the program exits.

提交回复
热议问题