Sunday, November 8, 2026
HomeArtificial IntelligenceProfiling Python Code

Profiling Python Code

[ad_1]

Profiling is a method to determine how time is spent in a program. With this statistics, we will discover the “scorching spot” of a program and take into consideration methods of enchancment. Typically, scorching spot in surprising location could trace a bug in this system as properly.

On this tutorial, we are going to see how we will use the profiling facility in Python. Particularly, you will note

  • How we will examine small code fragments utilizing timeit module
  • How we will profile all the program utilizing cProfile module
  • How we will invoke a profiler inside an current program
  • What the profiler can not do

Let’s get began.

Profiling Python Code. Photograph by Prashant Saini. Some rights reserved.

Tutorial Overview

This tutorial is in 4 elements; they’re:

  • Profiling small fragments
  • The profile module
  • Utilizing profiler inside code
  • Caveats

Profiling small fragments

When you’re requested concerning the alternative ways of doing the identical factor in Python, one perspective is to verify which one is extra environment friendly. In Python’s customary library, we’ve the timeit module that enables us to do some easy profiling.

For instance, to concatenate many quick strings, we will use the be part of() operate from strings or use the + operator. So how we all know which is quicker? Think about the next Python code:

It will produce an extended string 012345.... within the variabe longstr. Various method to write that is:

To match the 2, we will do the next on the command line:

These two instructions will produce the next output:

The above instructions is to load the timeit module and cross on a single line of code for measurement. Within the first case, we’ve two strains of statements and they’re handed on to the timeit module as two separate arguments. In the identical rationale, the primary command will also be offered as three strains of statements (by breaking the for loop into two strains), however the indentation of every line must be quoted appropriately:

The output of timeit is to seek out the most effective efficiency amongst a number of runs (default to be 5). Every run is to run the supplied statements a number of instances (which is dynamically decided). The time is reported as the common to execute the statements as soon as in the most effective run.

Whereas it’s true that the be part of operate is quicker than the + operator for string concatenation, the timing above is just not a good comparability. It’s as a result of we use str(x) to make quick strings on the fly throughout the loop. The higher method to do are the next:

which produces:

The -s possibility permits us to supply the “setup” code, which is executed earlier than the profiling and never timed. Within the above, we create the listing of quick strings earlier than we begin the loop. Therefore the time to create these strings aren’t measured within the “per loop” timing. From the above, we see that the be part of() operate is 2 orders of magnitude quicker than the + operator. The extra typically use of the -s possibility is to import the libraries. For instance, we will examine the sq. root operate from Python’s math module, from numpy, and utilizing the exponential operator ** as follows:

The above produces the next measurement, which we see that math.sqrt() is quickest whereas numpy.sqrt() is slowest on this specific instance:

For those who surprise why numpy is slowest, it’s as a result of numpy is optimized for arrays. You will note its distinctive velocity within the following different:

the place the result’s:

For those who want, it’s also possible to run timeit in Python code. For instance, the next might be just like the above, however provide the uncooked complete timing for every run:

Within the above, every run is to execute the assertion 10000 instances; the result’s as follows, which you’ll see the results of roughly 98 usec per loop in the most effective run:

The profile module

Give attention to an announcement or two for efficiency is from a microscopic perspective. Chances are high, we’ve an extended program and wish to see what’s inflicting it to run sluggish. That occurs earlier than we will take into account different statements or algorithms.

A program working sluggish can usually resulting from two causes: A component is working sluggish, or a component is working too many instances and that added as much as take an excessive amount of time. We name these “efficiency hogs” the recent spot. Let’s have a look at an instance. Think about the next program that makes use of hill climbing algorithm to seek out hyperparameters for a perceptron mannequin:

Assume we saved this program within the file hillclimb.py, we will run the profiler within the command line as follows:

and the output would be the following:

The conventional output of this system might be printed first, after which the profiler’s statistics might be printed. From the primary row, we see that the operate goal() in our program has run for 101 instances that took a complete of 4.89 seconds. However this 4.89 seconds are largely spent on the capabilities it referred to as, which the whole time that spent at that operate is merely 0.001 second. The capabilities from dependent modules are additionally profiled. Therefore you see numerous numpy capabilities above too.

The above output is lengthy and will not be helpful to you as it may be tough to inform which operate is the recent spot. Certainly we will type the above output. For instance, to see which operate is known as probably the most variety of instances, we will type by ncalls:

Its output is as follows, which says the get() operate from a Python dict is probably the most used operate (but it surely solely consumed 0.03 seconds in complete out of the 5.6 seconds to complete this system):

The opposite type choices are as follows:

Kind string That means
calls Name depend
cumulative Cumulative time
cumtime Cumulative time
file File title
filename File title
module File title
ncalls Name depend
pcalls Primitive name depend
line Line quantity
title Operate title
nfl Title/file/line
stdname Commonplace title
time Inside time
tottime Inside time

If this system takes a while to complete, it isn’t affordable to run this system many instances simply to seek out the profiling end in a distinct type order. Certainly, we will save the profiler’s statistics for additional processing, as follows:

Just like above, it would run this system. However this won’t print the statistics to the display screen however to put it aside right into a file. Afterwards, we will use the pstats module like following to open up the statistics file and supply us a immediate to control the info:

For instance, we will use type command to alter the type order and use stats to print what we noticed above:

You’ll discover that the stats command above permits us to supply an additional argument. The argument is usually a common expression to seek for the capabilities such that solely these matched might be printed. Therefore it’s a means to supply a search string to filter.

This pstats browser permits us to see extra than simply the desk above. The callers and callees instructions reveals us which operate calls which operate and what number of instances it’s referred to as, and the way a lot time it spent. Therefore we will take into account that as a breakdown of the operate degree statistics. It’s helpful when you have numerous capabilities that calls one another and wished to understand how the time spent in numerous eventualities. For instance, this reveals that the goal() operate is known as solely by the hillclimbing() operate however the hillclimbing() operate calls a number of different capabilities:

Utilizing profiler inside code

The above instance assumes you’ve gotten the whole program saved in a file and profile all the program. Typically, we concentrate on solely part of all the program. For instance, if we load a big module, it takes time to bootstrap and we wish to ignore this from profiling. On this case, we will invoke the profiler just for sure strains. An instance is as follows, which modified from this system above:

it would output the next:

Caveats

Utilizing profiler with Tensorflow fashions could not produce what you’d count on, particularly when you have written your personal customized layer or customized operate for the mannequin. For those who did it appropriately, Tenorflow supposed to construct the computation graph earlier than your mannequin is executed and therefore the logic might be modified. The profiler output will subsequently not displaying your customized lessons.

Equally for some superior modules that contain binary code. The profiler can see you referred to as some capabilities and marked it as “built-in” strategies but it surely can not go any additional into the compiled code.

Under is a brief code of LeNet5 mannequin for the MNIST classification drawback. For those who attempt to profile it and print the highest 15 rows, you will note {that a} wrapper is occupying majority of the time and nothing will be proven past that:

Within the consequence beneath, the TFE_Py_Execute is marked as “built-in” technique and it consumes 30.1 sec out of the whole run time of 39.6 sec. Be aware that the tottime is similar because the cumtime which means from profiler’s perspective, it appears all time are spent at this operate and it doesn’t name some other capabilities. This illustrates the limitation of Python’s profiler.

Lastly, Python’s profiler offers you solely the statistics on time however not reminiscence utilization. You could have to search for one other library or instruments for this function.

Additional Readings

The usual library modules timeit, cProfile, pstats have their documentation in Python’s documentation:

The usual library’s profiler could be very highly effective however not the one one. If you would like one thing extra visible, you’ll be able to check out the Python Name Graph module. It will probably produce an image of how capabilities calling one another utilizing the GraphViz software:

The limitation of not in a position to dig into the compiled code will be solved by not utilizing the Python’s profiler however as an alternative, use one for compiled applications. My favourite is Valgrind:

however to make use of it, you might have to recompile your Python interpreter to activate debugging assist.

Abstract

On this tutorial, we discovered what’s a profiler and what it will probably do. Particularly,

  • We all know how you can examine small code with timeit module
  • We see Python’s cProfile module can present us detailed statistics on how time is spent
  • We discovered to make use of the pstats module towards the output of cProfile to type or filter



[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments