Change language

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"  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"  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.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically