Using profile for Python code performance analysis

Source: Internet
Author: User

Locating program Performance Bottlenecks

The prerequisite for code optimization is to understand where the performance bottleneck is, where the main time of the program is consumed, and for more complex code to be located with tools, Python has built-in rich performance analysis tools such as Profile,cprofile and hotshot. The Profiler is a set of Python-brought programs that describe the performance of the program at runtime and provide various statistics to help the user locate the program's performance bottleneck. The Python standard module offers three types of profilers:cprofile,profile and hotshot.

Profile is very simple to use, just need to import before use. The concrete examples are as follows:

Profiling with profile

1 Import Profile2 defprofiletest ():3Total =1; 4     forIinchRange (10):  5total=total* (i+1)  6        Print Total7    return Total8 if __name__=="__main__":  9Profile.run ("profiletest ()")

The running results of the program are as follows:

Figure 1. Performance Analysis Results

The specific explanations for each column of the output are as follows:

Ncalls: Indicates the number of times the function was called;

Tottime: Indicates the total elapsed time of the specified function, and removes the run time of the calling child function in the function;

Percall: (the first percall) equals tottime/ncalls;

Cumtime: Represents the time that the call to the function and all its child functions runs, that is, when the function starts calling to the return time;

Percall: (the second percall) is the average time that a function is run, equal to Cumtime/ncalls;

Filename:lineno (function): The specific information of each function call;

If you need to save the output in the form of a log, simply add another parameter when you call it. such as Profile.run ("Profiletest ()", "Testprof").

Using profile for Python code performance analysis

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.