How do I profile a Python script?
By default, Python contains a profiler called cProfile
. It not only gives the total running time, but also times each function separately, and tells you how many times each function was called, making it easy to determine where you should make optimizations.
You can call it from within your code:
import cProfile
cProfile.run('foo()')
Even more usefully, you can invoke the cProfile
when running a script:
python -m cProfile myscript.py
With the output similar to this:
1007 function calls in 0.061 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.061 0.061 <string>:1(<module>)
1000 0.051 0.000 0.051 0.000 euler048.py:2(<lambda>)
1 0.005 0.005 0.061 0.061 euler048.py:2(<module>)
1 0.000 0.000 0.061 0.061 {execfile}
1 0.002 0.002 0.053 0.053 {map}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler objects}
1 0.000 0.000 0.000 0.000 {range}
1 0.003 0.003 0.003 0.003 {sum}
To learn more about cProfile
, you can visit the official documentation.
-
How do I check if a list is empty in Python?
You can check if a list is empty by using the len() function to check the length of the list. If the length of the list is 0, then it is empty. Here's an example: my_list = [] if len(my_list) == 0:...
Questions -
Getting the class name of an instance in Python?
You can use the built-in type() function to get the class name of an instance in Python. For example: class MyClass: pass myinstance = MyClass() print(type(myinstance).name) This will output My...
Questions -
What Does the “yield” Keyword Do in Python?
To better understand what yield does, you need first to understand what generator and iterable are. What is iterable When you use a list or list-like structure, you can read the values from the lis...
Questions -
What is the meaning of single and double underscore before an object name in Python?
In Python, single underscore _ before an object name means that the object is meant to be private, and shouldn't be directly accessed from outside the class. However, it is just a naming convention...
Questions