Accurate timing of functions in python

后端 未结 7 978
一向
一向 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:58

    You can create a "timeme" decorator like so

    import time                                                
    
    def timeme(method):
        def wrapper(*args, **kw):
            startTime = int(round(time.time() * 1000))
            result = method(*args, **kw)
            endTime = int(round(time.time() * 1000))
    
            print(endTime - startTime,'ms')
            return result
    
        return wrapper
    
    @timeme
    def func1(a,b,c = 'c',sleep = 1):
        time.sleep(sleep)
        print(a,b,c)
    
    func1('a','b','c',0)
    func1('a','b','c',0.5)
    func1('a','b','c',0.6)
    func1('a','b','c',1)
    
    0 讨论(0)
提交回复
热议问题