Problems – To find where the program spends its time and make timing measurements.
To simply time the whole program, it’s usually easy enough to use something like the Unix time command as shown below.
Code #1 : Command to time the whole program
On the other extreme, to have a detailed report showing what the program is doing, cProfile module is used.
Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 263169 0.080 0.000 0.080 0.000 someprogram.py:16(frange) 513 0.001 0.000 0.002 0.000 someprogram.py:30(generate_mandel) 262656 0.194 0.000 15.295 0.000 someprogram.py:32() 1 0.036 0.036 16.077 16.077 someprogram.py:4() 262144 15.021 0.000 15.021 0.000 someprogram.py:4(in_mandelbrot) 1 0.000 0.000 0.000 0.000 os.py:746(urandom) 1 0.000 0.000 0.000 0.000 png.py:1056(_readable) 1 0.000 0.000 0.000 0.000 png.py:1073(Reader) 1 0.227 0.227 0.438 0.438 png.py:163() 512 0.010 0.000 0.010 0.000 png.py:200(group)
More often than not, profiling the code lies somewhere in between these two extremes. For example, if one already knows that the code spends most of its time in a few selected functions. For selected profiling of functions, a short decorator can be useful.
Code #3: Using short decorator for selected profiling of functions
To use the decorator, simply place it in front of a function definition to get timings from it as shown in the code below.
Code #4 :
__main__.countdown : 0.803001880645752
Code #5: Defining a context manager to time a block of statements.
Code #6: How the context manager works
counting : 1.5551159381866455
Code #7 : Using timeit module to study the performance of small code fragments
timeit works by executing the statement specified in the first argument a million times and measuring the time.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course