Recently, we were testing all the endpoints of one of our products to find out
- Every endpoint is returning the expected result.
- The response time of a particular endpoint should be < 300ms
- Improve existing code base based on the result.
While testing we found one of the endpoints taking more time than we expected.
It intrigued us to review the code segment of that particular endpoint. There were 78 lines of code and it was quite difficult for us to figure out which particular code segment we should refactor. At the first glance, we thought some of the DateTime comparisons were taking more time. Even after simplifying that code segment, the response time didn’t change much.
Then it came to our mind that we should profile our code. After doing some google searches on how people are profiling their python code, we found some interesting ways to do it. There are some tools that also support the visualization of profiling results. More details on this Stackoverflow link.
The easiest way to profile python code using built-in cProfile
package.
import cProfiledef sum(a, b):
return a+bif __name__ == '__main__':
pr = cProfile.Profile()
pr.enable()
sum(2, 3)
pr.disable()
pr.print_stats()
It will show the result in stdout
It’s possible to store the output of the result in a file instead of showing stdout
pr.dump_stats("result.txt")
There are a few other options you can explore, take a look at the python profiling documentation.