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

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

    This is Paul McGuire's answer that works for me. Just in case someone was having trouble running that one.

    import atexit
    from time import clock
    
    def reduce(function, iterable, initializer=None):
        it = iter(iterable)
        if initializer is None:
            value = next(it)
        else:
            value = initializer
        for element in it:
            value = function(value, element)
        return value
    
    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)
    
    def endlog():
        end = clock()
        elapsed = end-start
        log("End Program", secondsToStr(elapsed))
    
    def now():
        return secondsToStr(clock())
    
    def main():
        start = clock()
        atexit.register(endlog)
        log("Start Program")
    

    Call timing.main() from your program after importing the file.

提交回复
热议问题