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

后端 未结 30 1662
甜味超标
甜味超标 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: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 ;).

提交回复
热议问题