We discuss in this article how you can insert timing routines for measuring the time spent in a specific part of a program.
By inserting timing routines to a program, the time spent in specific parts of the program can be measured.
In order to get a bigger picture of the performance of a program, it can be useful to measure the time spent in a specific region of the program. The region can be a function, or just a part of a function, and the region can contain calls to other functions. In a typical usage pattern one obtains a value from some “clock” (normally in units of seconds) at the beginning and end of the region and by subtracting the two values one obtains the time spent in the region.
Python standard library has a time module which provides various time-related functions. In particular the time.process_time function can be used for measuring a specific region:
Many Python based simulation programs provide at the end of a run a timing report, which is often generated with application’s own timers. As an example a snippet from the output of quantum mechanical simulation software GPAW:
Python context managers provide a nice feature for executing functions when entering and exiting a region. The example below shows how one can utilize a context manager and the with statement for timing a part of a code. If you are not familiar with context managers you can find more information here.