This article describes how to count the time consumed by function running in Python. It involves the skills related to Python time operations and is very simple and practical, for more information about how to count the running time of functions in Python, see the following example. Share it with you for your reference. The specific implementation method is as follows:
Import timedef time_me (fn): def _ wrapper (* args, ** kwargs): start = time. clock () fn (* args, ** kwargs) print "% s cost % s second" % (fn. _ name __, time. clock ()-start) return _ wrapper # This decorator can conveniently count the time consumed by function running. # It is best to analyze the script performance. # Use this method: @ time_medef test (x, y): time. sleep (0.1) @ time_medef test2 (x): time. sleep (0.2) test (1, 2) test2 (2) # output: # test cost 0.1001529524 second # test2 cost 0.199968431742 second
Another more advanced version is:
import timeimport functoolsdef time_me(info="used"): def _time_me(fn): @functools.wraps(fn) def _wrapper(*args, **kwargs): start = time.clock() fn(*args, **kwargs) print "%s %s %s"%(fn.__name__, info, time.clock() - start), "second" return _wrapper return _time_me@time_me()def test(x, y): time.sleep(0.1)@time_me("cost")def test2(x): time.sleep(0.2)test(1, 2)test2(2)
I hope this article will help you with Python programming.