Python | Timing and profiling of the program

To simply time the entire program, it is usually sufficient to simply use something like the Unix time command, as shown below.

Code # 1: The whole program time command

bash % time python3 someprogram.py

real 0m13 . 937s

user 0m12 . 162s

sys 0m0 . 098s

bash %

On the other hand, for getting a detailed report on what you are doing t program, used module cProfile .

bash % python3 - m cProfile someprogram.py

Output:

 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) 

Most often, code profiling falls somewhere between these two extremes. For example, if you already know that your code spends most of its time in a few selected functions. A short decorator can be useful for the selected feature profiling.

Code # 3: Using a short decorator for the selected feature profiling

# abc.py

  

import time

from functools import wraps

 

def timethis (func):

@ wraps (func)

def wrapper ( * args, * * kwargs):

start = time.perf_counter ()

r = func ( * args, * * kwargs)

end = time.perf_counter ( )

print ( `{}. {}: {}` . format (func .__ module__, func .__ name__, end - start))

return r

return wrapper

To use a decorator, just place it in front of the function definition to get the time from it, as shown in the code below. 
Code # 4:

@ abc

def countdown (n):

while n & gt;  0 :

n - = 1

 

countdown ( 10000000 )

Exit:

 __main __. countdown: 0.803001880645752 

Code # 5: Define a context manager to determine the timing of a statement block.

from contextlib import contextmanager

 

def timeblock (label):

start = time.perf_counter ()

try :

yield

finally :

end = time.perf_counter ()

print ( `{}: {}` . format (label, end - start))

Code # 6: How ra the context manager is working

with timeblock ( `counting` ):

n = 10000000

  while n & gt;  0 :

n - = 1

Output:

 counting: 1.5551159381866455 

Code # 7: Using the timeit module to examine the performance of small snippets of code

from timeit import timeit

print (timeit ( `math.sqrt (2)` , `import math` ), "" )

  

print (timeit ( `sqrt (2)` , `from math import sqrt` ))

Output:

 0.1432319980012835 0.10836604500218527 

timeit works by executing the operator specified in the first argument a million times and measuring the time.