Measuring the performance of Python chunks in different environments

There are many libraries for measuring the performance of Python code. These tools are called profiling tools.

Even the Python core library has its own, it’s a bit cumbersome to use it, and, usually, they were not created for living with our production code.

Some examples are:

  • timeit
  • profile
  • cprofile

Today, I’ll present you a tiny library for easy measure-specific chunks of Python code in a straightforward way.

Let’s just say we have this code:

After executing the above code, we could not be sure what of them was the bottleneck of our program.

As I told you, it is possible to use timeit, for example:

But it’s not intuitive and hard to use in real scenarios.

Imagine, for example, a simple web application that uses the above 3 functions and:

  1. We want to measure the time taken for each of them.
  2. We don’t want to change the source code depending on the environment where our app is running,
  3. We want that only work in the development and staging environment.

Did you get it? Right. Let’s write our sample web application:

Currently, we cannot measure the time taken for each function and detect the possible bottlenecks.

So, we need python-performance-tools library:

After running the web app and visiting the url:, you can see something like:

Nice! Now we know how long it takes to execute each function!

But… as I told you, we only want to execute the profiling on development and staging steps. Ok, let’s do it:

The catch_time has a second optional argument. This argument is an activation function. This is: a function that should return a boolean and only will be activated if it returns a True.

Check then if it works.

Enabling profiling

Disabling profiling


  1. Python core profiling library:
  2. Python timeit:
  3. Python Performance tools:



REST API Cybersecurity and Hacking & Python Architect. +100 GitHub projects. Speaker

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store

REST API Cybersecurity and Hacking & Python Architect. +100 GitHub projects. Speaker