How to Check the Execution Time of Python Script?

Introduction

The time module can be used to determine how long a Python script will take to execute. Import it first at the start of your script. Next, use time to record the start time.time() prior to the desired measurement code block, and note the final time following that block. To find the execution time, compute the difference between the start and end times. Lastly, record or publish the outcome. Using this technique, you can ensure effective execution by analyzing the performance of your code and optimizing it as necessary.

Numerous Python modules, such as time, timeit, and datetime, are capable of storing the time at which a specific program segment is running. We can determine how long it took to complete a section by adjusting or obtaining the difference between the starting and finishing times at which that section is being completed.

Techniques to Calculate Time Difference

The time difference can be calculated using the following techniques:

  • The Python time module is a collection of several time-related functions that are housed inside common utility modules. The time since the epoch is retrieved in seconds using its time.time() function. The reference time, usually January 1, 1970, is referred to as the epoch. Nevertheless, the way leap seconds are handled differs throughout systems, which has an impact on the precision of the result. Depending on the underlying system, leap seconds-adjustments made to maintain atomic time in accordance with astronomical time-are handled differently. As a result, although time.time() offers a simple way to retrieve time information, its accuracy with respect to leap seconds may vary depending on the system.
  • Functions for organizing dates and times are introduced by the Python datetime package. Located deep within the module, its now() function is a vital resource for finding the current local date and time. It returns a datetime object that represents the current time when it is called. Details including the year, month, day, hour, minute, second, and microsecond are contained in this item. Developers may easily include real-time timestamps into their programs with now(), making it easier to do things like scheduling operations, logging occurrences, and gathering temporal data for reporting and analysis inside the Python environment.
  • The Python timeit module runs a code snippet a defined number of times (1,000,000 by default) in order to undertake thorough code performance evaluations. This long iteration guarantees timing measurements that are statistically significant, improving the precision of execution time evaluations. Timeit reduces the impact of outside variables like as system load or varying resources by repeatedly executing the code.

This helps developers make more informed decisions on how efficient their code is, supports optimization efforts, and encourages performance-driven development approaches.

Checking the Python Execution Time with the time Module

Calculating the duration of a code segment by logging its beginning and ending times

Using timestamps, developers frequently track the beginning and ending times of a code segment to determine its duration. The time module or datetime module in Python must be used to record the current time both before and after the segment is executed. The elapsed duration can be calculated by deducting the beginning and ending times. With this method, code execution time can be precisely measured, which makes it easier to analyze, optimize, and fine-tune important parts of software applications.

Example

Output:

Duration: 0.0776059627532959 seconds

Explanation

The above example of Python code counts the duration of a code section exactly by using the time module. The current time is first recorded using time.time() and assigned to start_time. Once the designated segment has been executed, the code iterates a for loop one million times. As soon as the segment ends, it then captures the current time and saves it in end_time. The code determines how much time has passed since the segment began by deducting start_time from end_time. When it comes to optimizing and refining efforts, developers are given vital information into the performance characteristics of their code by printing this length in seconds.

Measuring Time Taken for a Code Segment by Adding Up the Time Required Per Iteration

When determining the total time needed for a code segment, the starting time prior to the segment's execution is recorded, and the elapsed time is computed following each iteration. This technique offers a finer-grained view of the code's performance and is especially helpful for sections that run repeatedly. Developers can obtain a comprehensive grasp of the variations in the code's efficiency across several executions by gradually adding up the time required for each iteration. This method makes it possible to identify possible coding bottlenecks or regions that could benefit from optimization, which eventually results in software that is more responsive and efficient.

Example

Output:

Total duration: 0.22059369087219238 seconds
Overall duration: 0.8168423175811768 seconds

Explanation

This Python code shows how to calculate the duration of a code segment by adding up the time needed for each iteration. The total_duration variable is initialized and the number of iterations is set to 1,000,000 at the start. Before the loop is executed, the script records the beginning time. Iterating through the designated range, the loop records the beginning and ending times of each iteration. Next, it determines how long each iteration lasts and adds that information to the total_duration variable. Once every iteration is finished, the script records the final time. The beginning and ending times are subtracted to determine the overall duration. Lastly, the overall_duration (the total time required for the entire loop) and total_duration (the sum of the various iteration durations) are printed, offering insights into the performance of the code segment.

Checking the Execution Time with the DateTime Module

To verify the execution time of a code segment, use the DateTime module to record the current time both before and after the code segment is executed. First, import the module called datetime. Next, use datetime.datetime.now() to capture the beginning time just prior to the code segment. Make a comparable note of the execution's conclusion time. The duration can be calculated by deducting the beginning and finishing times. Code execution time can be measured precisely with datetime's microsecond precision thanks to this method. Datetime offers flexibility in time-related processes beyond simple time measurement by including features for managing dates, times, and time intervals.

Example

Output:

Duration: 0:00:00.168564

Explanation

This Python code calculates a code segment's execution time by using the DateTime module. First, it uses datetime to capture the current time prior to the function running.start_time is where datetime.now() is stored. The code segment takes the current time once more and assigns it to end_time once it runs (represented by a for loop in this case). The code determines how long the code section will run by deducting start_time from end_time. The length that is obtained offers valuable information about the code's performance, allowing engineers to evaluate its effectiveness. This method makes performance optimization efforts easier and delivers very accurate time measurement.

Examining the Execution Time with the timeit Module

The Python timeit module makes it easier to measure code execution time precisely by running the code several times and average the results to reduce variability. Import the timeit module first. Next, include the code section and the number of repetitions and iterations in a call to the timeit.timeit() function. Timing measurements are statistically important thanks to this strategy. Timeit also provides a Timer class for even more precise timing control. Developers may pinpoint performance bottlenecks and effectively adjust their code to improve the overall effectiveness and responsiveness of their apps by receiving precise timing information.

Output

Execution time: 0.12642394900001364 seconds

Explanation

This Python example uses the timeit module to measure a code segment's execution time exactly. The section is contained in the code_to_measure variable, which is here shown by a for loop. The code segment is run once (number=1) using the timeit.timeit() function, and the execution time is determined. This approach averages several executions to guarantee statistical relevance. The measured execution time is printed at the end. Developers can use timeit to obtain precise insights about the performance of their code, which helps with optimization efforts to improve responsiveness and efficiency. By locating and resolving performance bottlenecks, this method eventually raises the standard of software programs as a whole.