Measuring the time it takes for a function to run and complete in Python

后端 未结 3 1371
悲哀的现实
悲哀的现实 2021-01-13 03:01

In Python 3.4.1, I\'m trying to measure how long it takes for a function to run and complete then recording it. I\'m currently doing it this like so:

startti         


        
3条回答
  •  爱一瞬间的悲伤
    2021-01-13 03:56

    I generally use this decorator to time my functions:

    import time                                                
    def timeit(method):
        def timed(*args, **kw):
            ts = time.time()
            result = method(*args, **kw)
            te = time.time()
            print '%r (%r, %r) %2.2f sec' % \
                  (method.__name__, args, kw, te-ts)
            return result
    
        return timed
    
    @timeit
    def timeme():
        time.sleep(3)
    

    time.time() gives more precise time for benchmarks than time.clock() primarily because time.clock() measures CPU time. time.time() will return seconds passed since epoch (i.e. wall time), which is what you need.

    Or you can also use timeit https://docs.python.org/3/library/timeit.html

提交回复
热议问题