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

后端 未结 30 1690
甜味超标
甜味超标 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 02:42

    I put this timing.py module into my own site-packages directory, and just insert import timing at the top of my module:

    import atexit
    from time import clock
    
    def secondsToStr(t):
        return "%d:%02d:%02d.%03d" % \
            reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
                [(t*1000,),1000,60,60])
    
    line = "="*40
    def log(s, elapsed=None):
        print line
        print secondsToStr(clock()), '-', s
        if elapsed:
            print "Elapsed time:", elapsed
        print line
        print
    
    def endlog():
        end = clock()
        elapsed = end-start
        log("End Program", secondsToStr(elapsed))
    
    def now():
        return secondsToStr(clock())
    
    start = clock()
    atexit.register(endlog)
    log("Start Program")
    

    I can also call timing.log from within my program if there are significant stages within the program I want to show. But just including import timing will print the start and end times, and overall elapsed time. (Forgive my obscure secondsToStr function, it just formats a floating point number of seconds to hh:mm:ss.sss form.)

    Note: A Python 3 version of the above code can be found here or here.

提交回复
热议问题