Measure the time consumed by functions in Python.

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.