Python | Timing and Profiling the program Last Updated : 12 Jun, 2019 Summarize Comments Improve Suggest changes Share Like Article Like Report 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 Python3 1== bash % time python3 someprogram.py real 0m13.937s user 0m12.162s sys 0m0.098s bash % On the other extreme, to have a detailed report showing what the program is doing, cProfile module is used. Python3 1== 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) 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 Python3 1== # 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 the decorator, simply place it in front of a function definition to get timings from it as shown in the code below. Code #4 : Python3 1== @abc def countdown(n): while n > 0: n -= 1 countdown(10000000) Output : __main__.countdown : 0.803001880645752 Code #5: Defining a context manager to time a block of statements. Python3 1== 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 the context manager works Python3 1== with timeblock('counting'): n = 10000000 while n > 0: n -= 1 Output : counting : 1.5551159381866455 Code #7 : Using timeit module to study the performance of small code fragments Python3 1== from timeit import timeit print (timeit('math.sqrt(2)', 'import math'), "\n") print (timeit('sqrt(2)', 'from math import sqrt')) Output : 0.1432319980012835 0.10836604500218527 timeit works by executing the statement specified in the first argument a million times and measuring the time. Comment More infoAdvertise with us Next Article Python | Timing and Profiling the program M manikachandna97 Follow Improve Article Tags : Python python-utility Practice Tags : python Similar Reads Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo 10 min read Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth 15+ min read Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p 11 min read Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list 10 min read Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test 9 min read Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co 11 min read Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien 3 min read Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes 9 min read Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is 8 min read Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam 3 min read Like