Get time of execution of a block of code in Python 2.7

后端 未结 6 715
北荒
北荒 2020-12-07 08:52

I would like to measure the time elapsed to evaluate a block of code in a Python program, possibly separating between user cpu time, system cpu time and elapsed time.

<
6条回答
  •  不知归路
    2020-12-07 09:18

    I always use a decorator to do some extra work for a existing function, including to get the execution time. It is pythonic and simple.

    import time
    
    def time_usage(func):
        def wrapper(*args, **kwargs):
            beg_ts = time.time()
            retval = func(*args, **kwargs)
            end_ts = time.time()
            print("elapsed time: %f" % (end_ts - beg_ts))
            return retval
        return wrapper
    
    @time_usage
    def test():
        for i in xrange(0, 10000):
            pass
    
    if __name__ == "__main__":
        test()
    

提交回复
热议问题