Accurate timing of functions in python

后端 未结 7 1024
一向
一向 2020-11-30 19:23

I\'m programming in python on windows and would like to accurately measure the time it takes for a function to run. I have written a function \"time_it\" that takes another

7条回答
  •  一生所求
    2020-11-30 19:50

    If you want to time a python method even if block you measure may throw, one good approach is to use with statement. Define some Timer class as

    import time
    
    class Timer:    
        def __enter__(self):
            self.start = time.clock()
            return self
    
        def __exit__(self, *args):
            self.end = time.clock()
            self.interval = self.end - self.start
    

    Then you may want to time a connection method that may throw. Use

    import httplib
    
    with Timer() as t:
        conn = httplib.HTTPConnection('google.com')
        conn.request('GET', '/')
    
    print('Request took %.03f sec.' % t.interval)
    

    __exit()__ method will be called even if the connection request thows. More precisely, you'd have you use try finally to see the result in case it throws, as with

    try:
        with Timer() as t:
            conn = httplib.HTTPConnection('google.com')
            conn.request('GET', '/')
    finally:
        print('Request took %.03f sec.' % t.interval)
    

    More details here.

提交回复
热议问题