[Tut] How to Measure Elapsed Time in Python? - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Measure Elapsed Time in Python? (/thread-99340.html) |
[Tut] How to Measure Elapsed Time in Python? - xSicKxBot - 05-05-2022 How to Measure Elapsed Time in Python? <div><p class="has-global-color-8-background-color has-background"><strong>Summary: </strong>You can evaluate the execution time of your code by saving the timestamps using <code>time.time()</code> at the beginning and the end of your code. Then, you can find the difference between the start and the end timestamps that results in the total execution time.</p> <hr class="wp-block-separator is-style-wide" /> <div id="ez-toc-container" class="ez-toc-v2_0_19 counter-hierarchy counter-decimal ez-toc-light-blue"> <div class="ez-toc-title-container"> <p class="ez-toc-title">Table of Contents</p> <p><span class="ez-toc-title-toggle"><a class="ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle" style="display: none;"><i class="ez-toc-glyphicon ez-toc-icon-toggle"></i></a></span></div> <nav> <ul class="ez-toc-list ez-toc-list-level-1"> <li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-1" href="https://blog.finxter.com/how-to-measure-elapsed-time-in-python/#Method_1_Using_timetime" title="Method 1: Using time.time()">Method 1: Using time.time()</a></li> <li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-2" href="https://blog.finxter.com/how-to-measure-elapsed-time-in-python/#Method_2_Using_timeperf_counter" title="Method 2: Using time.perf_counter()">Method 2: Using time.perf_counter()</a></li> <li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-3" href="https://blog.finxter.com/how-to-measure-elapsed-time-in-python/#Method_3_Using_timeprocess_time" title="Method 3: Using time.process_time()">Method 3: Using time.process_time()</a></li> <li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-4" href="https://blog.finxter.com/how-to-measure-elapsed-time-in-python/#Method_4_Using_Timeit_Module" title="Method 4: Using Timeit Module">Method 4: Using Timeit Module</a> <ul class="ez-toc-list-level-3"> <li class="ez-toc-heading-level-3"><a class="ez-toc-link ez-toc-heading-5" href="https://blog.finxter.com/how-to-measure-elapsed-time-in-python/#41_Using_timeittimeit" title="4.1 Using timeit.timeit()">4.1 Using timeit.timeit()</a></li> <li class="ez-toc-page-1 ez-toc-heading-level-3"><a class="ez-toc-link ez-toc-heading-6" href="https://blog.finxter.com/how-to-measure-elapsed-time-in-python/#42_Using_timeitrepeat" title="4.2 Using timeit.repeat">4.2 Using timeit.repeat</a></li> <li class="ez-toc-page-1 ez-toc-heading-level-3"><a class="ez-toc-link ez-toc-heading-7" href="https://blog.finxter.com/how-to-measure-elapsed-time-in-python/#43_Using_timeitdefault_timer" title="4.3 Using timeit.default_timer()">4.3 Using timeit.default_timer()</a></li> </ul> </li> <li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-8" href="https://blog.finxter.com/how-to-measure-elapsed-time-in-python/#Methdo_5_Using_datetimedatetimenow" title="Methdo 5: Using datetime.datetime.now()">Methdo 5: Using datetime.datetime.now()</a></li> <li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-9" href="https://blog.finxter.com/how-to-measure-elapsed-time-in-python/#Conclusion" title="Conclusion">Conclusion</a></li> </ul> </nav> </div> <p><strong>Problem: </strong>Given a Python program; how will you measure the elapsed time ( the time taken by the code to complete execution)?</p> <p>Consider the following snippet:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import time def perimeter(x): time.sleep(5) return 4 * x def area(x): time.sleep(2) return x * x p = perimeter(8) print("Perimeter: ", p) a = area(8) print("Area: ", a)</pre> <ul> <li><strong>Challenges: </strong> <ul> <li>How will you find the time taken by each function in the above program to execute?</li> <li>How will you compute the total time elapsed by the entire code?</li> </ul> </li> </ul> <p class="has-background" style="background-color:#a9d4ff"><strong>Tidbit</strong>: <code>sleep()</code> is a built-in method of the <code>time</code><strong> </strong>module in Python that is used to delay the execution of your code by the number of seconds specified by you.</p> <p>Now, let us conquer the given problem and dive into the solutions.</p> <h2><strong>Method 1: Using time.time()</strong></h2> <p><code>time.time()</code> is a function of the <code>time</code> module in Python that is used to get the time in seconds since the epoch. It returns the output, i.e., the time elapsed, as a floating-point value. </p> <p><strong>The code:</strong></p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import time def perimeter(x): time.sleep(5) return 4 * x def area(x): time.sleep(2) return x * x begin = time.time() start = time.time() p = perimeter(8) end = time.time() print("Perimeter: ", p) print("Time Taken by perimeter(): ", end - start) start = time.time() a = area(8) end = time.time() print("Area: ", a) print("Time Taken by area(): ", end - start) end = time.time() print("Total time elapsed: ", end - begin)</pre> <p><strong>Output:</strong></p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Perimeter: 32 Time Taken by Perimeter(): 5.0040647983551025 Area: 64 Time Taken by area(): 2.0023691654205322 Total time elapsed: 7.006433963775635</pre> <p><strong>Approach:</strong> <br />➤ Keep track of the time taken by each function by saving the time stamp at the beginning of each function with the help of a start variable and using the <code>time()</code> method.<br />➤ Similarly, the end time, i.e., the timestamp at which a function completes its execution, is also tracked with the help of the <code>time()</code> function at the end of each function.<br />➤ Finally, the difference between the end and the start time gives the total time taken by a particular function to execute. <br />➤ To find the total time taken by the entire program to complete its execution, you can follow a similar approach by saving the time stamp at the beginning of the program and the time stamp at the end of the program and then find their difference.</p> <p><strong>Discussion: </strong>If you are working on Python 3.3 or above, then another option to measure the elapsed time is <code>perf_counter</code> or <code>process_time</code>, depending on the requirements. Prior to Python 3.3, you could have used <code>time.clock</code>, however, it has been currently deprecated and is not recommended.</p> <h2><strong>Method 2: Using time.perf_counter()</strong></h2> <p>In Python, the <code>perf_counter()</code> function from the time module is used to calculate the execution time of a function and gives the most accurate time measure of the system. The function returns the system-wide time and also takes the sleep time into account.</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import time def perimeter(x): time.sleep(5) return 4 * x def area(x): time.sleep(2) return x * x begin = time.perf_counter() start = time.perf_counter() p = perimeter(8) end = time.perf_counter() print("Perimeter: ", p) print("Time Taken by perimeter(): ", end - start) start = time.perf_counter() a = area(8) end = time.perf_counter() print("Area: ", a) print("Time Taken by area(): ", end - start) end = time.perf_counter() print("Total time elapsed: ", end - begin)</pre> <p><strong>Output:</strong></p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Perimeter: 32 Time Taken by perimeter(): 5.0133558 Area: 64 Time Taken by are(): 2.0052768 Total time elapsed: 7.0189293</pre> <p><strong>Caution:</strong> The <code>perf_counter()</code> function not only counts the time elapsed along with the sleep time, but it is also affected by other programs running in the background on the system. Hence, you must keep this in mind while using <code>perf_counter</code> for performance measurement. It is recommended that if you utilize the <code>perf_counter()</code> function, ensure that you run it several times so that the average time would give an accurate estimate of the execution time.</p> <h2><strong>Method 3: Using time.process_time()</strong></h2> <p>Another method from the time module used to estimate the execution time of the program is <code>process_time()</code>. The function returns a float value containing the sum of the system and the user CPU time of the program. The major advantage of the <code>process_time()</code> function is that it does not get affected by the other programs running in the background on the machine, and it does not count the sleep time.</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import time def perimeter(x): time.sleep(5) return 4 * x def area(x): time.sleep(2) return x * x begin = time.process_time() start = time.process_time() p = perimeter(8) end = time.process_time() print("Perimeter: ", p) print("Time Taken by perimeter(): ", end - start) start = time.process_time() a = area(8) end = time.process_time() print("Area: ", a) print("Time Taken by area(): ", end - start) end = time.process_time() print("Total time elapsed: ", end - begin)</pre> <p><strong>Output:</strong></p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Perimeter: 32 Time Taken by perimeter(): 5.141000000000173e-05 Area: 64 Time Taken by area(): 4.1780000000005146e-05 Total time elapsed: 0.00029919000000000473</pre> <h2><strong>Method 4: <strong>Using Timeit Module</strong></strong></h2> <p><code>timeit</code> is a very handy module that allows you to measure the elapsed time of your code. A major advantage of using the timeit module is its ability to measure and execute lambda functions by specifying the number of executions. </p> <p><strong>Note: </strong>The <code>timeit</code> module turns off the garbage collection process temporarily while calculating the execution time.</p> <p>Let us dive into the different methods of this module to understand how you can use it to measure execution time within your code.</p> <h3><strong>4.1 Using timeit.timeit()</strong></h3> <p><strong>Example 1: </strong>In the following example, we will have a look at a lambda function being executed with the help of the timeit module such that we will be specifying the number of times this anonymous function will be executed and then calculate the time taken to execute it. </p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="12" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import timeit count = 1 def foo(x): global count print(f'Output for call{count} = {x * 3}') count += 1 a = timeit.timeit(lambda: foo(8), number=3) print("Time Elapsed: ", a)</pre> <p><strong>Output:</strong></p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Output for call1 = 24 Output for call2 = 24 Output for call3 = 24 Time Elapsed: 6.140000000000312e-05</pre> <p><strong>Explanation: </strong>After importing the <code>timeit</code> module, you can call the lambda function within the <code>timeit.timeit()</code> function as a parameter and also specify the number of times the function will be called with the help of the second parameter, i.e., number. In this case, we are calling the lambda function three times and printing the output generated by the function every time. Finally, we displayed the total time elapsed by the function. </p> <h3><strong>4.2 <strong>Using timeit.repeat</strong></strong></h3> <p>Even though the above method allowed us to calculate the execution time of a lambda function, it is not safe to say that the value evaluated by the <code>timeit()</code> function was accurate. To get a more accurate result, you can record multiple values of execution time and then find their mean to get the best possible outcome. This is what <code>timeit.repeat()</code> function allows you to do.</p> <p><strong>Example:</strong></p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="12-17" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import timeit count = 1 def foo(x): global count print(f'Output for call{count} = {x * 3}') count += 1 a = timeit.repeat(lambda: foo(8), number=1, repeat=3) print(a) s = 0 for i in a: s = s + i print("Best Outcome: ", s)</pre> <p><strong>Output:</strong></p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Output for call1 = 24 Output for call2 = 24 Output for call3 = 24 [5.160000000001275e-05, 1.3399999999996748e-05, 1.0399999999993748e-05] Best Outcome: 7.540000000000324e-05</pre> <h3><strong>4.3 Using timeit.default_timer()</strong></h3> <p>Instead of using <code>timeit.timeit()</code> function, we can also use the <code>timeit.default_timer()</code>, which is a better option as it provides the best clock available based on the platform and Python version you are using, thereby generating more accurate results. Using <code>timeit.default_timer()</code> is quite similar to using <code>time.time()</code>.</p> <p><strong>Example: </strong></p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import timeit import time def perimeter(x): time.sleep(5) return 4 * x def area(x): time.sleep(2) return x * x begin = timeit.default_timer() start = timeit.default_timer() p = perimeter(8) end = timeit.default_timer() print("Perimeter: ", p) print("Time Taken by Perimeter(): ", end - start) start = timeit.default_timer() a = area(8) end = timeit.default_timer() print("Area: ", a) print("Time Taken by Perimeter(): ", end - start) end = timeit.default_timer() print("Total time elapsed: ", end - begin)</pre> <p><strong>Output:</strong></p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Perimeter: 32 Time Taken by Perimeter(): 5.0143883 Area: 64 Time Taken by Perimeter(): 2.0116591 Total time elapsed: 7.0264410999999996</pre> <h2><strong>Methdo 5: Using datetime.datetime.now()</strong></h2> <p>The elapsed time can also be calculated using the <code>DateTime.datetime.now() </code>function from the datetime module in Python. The output of the method is represented as days, hours, and minutes. However, the disadvantage of this method is that it is slower than the <code>timeit()</code> module since calculating the difference in time is also included in the execution time.</p> <p><strong>Example:</strong></p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import datetime import time def perimeter(x): time.sleep(5) return 4 * x def area(x): time.sleep(2) return x * x begin = datetime.datetime.now() start = datetime.datetime.now() p = perimeter(8) end = datetime.datetime.now() print("Perimeter: ", p) print("Time Taken by Perimeter(): ", end - start) start = datetime.datetime.now() a = area(8) end = datetime.datetime.now() print("Area: ", a) print("Time Taken by Perimeter(): ", end - start) end = datetime.datetime.now() print("Total time elapsed: ", end - begin)</pre> <p><strong>Output:</strong></p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Perimeter: 32 Time Taken by Perimeter(): 0:00:05.003221 Area: 64 Time Taken by Perimeter(): 0:00:02.011262 Total time elapsed: 0:00:07.014483</pre> <h2><strong>Conclusion</strong></h2> <p>Thus to sum things up, you can use one of the following modules in Python to calculate the elapsed time of your code:</p> <ul> <li>The time module</li> <li>The timeit module</li> <li>The datetime module </li> </ul> <p>With that, we come to the end of this tutorial, and I hope you found it helpful. Please <strong><a rel="noreferrer noopener" href="https://blog.finxter.com/subscribe/" target="_blank">subscribe</a></strong> and <strong><a rel="noreferrer noopener" href="https://www.youtube.com/channel/UCRlWL2q80BnI4sA5ISrz9uw" target="_blank">stay tuned</a></strong> for more interesting articles. </p> <p>Here’s a list of highly recommended tutorials if you want to dive deep into the execution time of your code and much more:</p> <ul> <li><strong><a href="https://blog.finxter.com/pythons-time-clock-vs-time-time-detailed-comparsion/" target="_blank" rel="noreferrer noopener">Python’s time.clock() Vs. time.time() – A Detailed Comparison</a></strong></li> <li><strong><a href="https://blog.finxter.com/time-delay-in-python/">Time Delay in Python</a></strong></li> <li><strong><a href="https://blog.finxter.com/get-the-current-time-python/" target="_blank" rel="noreferrer noopener">How to Get the Current Time in Python?</a></strong></li> <li><strong><a href="https://blog.finxter.com/a-gentle-introduction-to-pythons-time-module/" target="_blank" rel="noreferrer noopener">A Gentle Introduction to Python’s Time Module</a></strong></li> </ul> </div> https://www.sickgaming.net/blog/2022/05/01/how-to-measure-elapsed-time-in-python/ |