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