Application of Decorators (2): time a function in Python

Timing a function is one way to evaluate its performance. This post demonstrates how to use decorator to time a function.

Timing a function Directly

It is very straightforward, if we want to time a function directly. The code snippet below demonstrate how to do it.

Timing a function Using Decorator

With decorator, the code for timing can be reused. Below is an example implementation of a timer decorator.

The example below demonstrates how the above decorator can be used to time functions.

It is very interesting to see that multi-threading does not run faster. I will explain this in a different post.

Written by

Senior Software Engineer

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