- How to Get time of a Python program’s execution
- Calculate Execution Time using time() Function
- Calculate execution time using timeit() function
- Calculate execution time using time.clock() Function
- Note:
- Calculate execution time using datetime.now() Function
- Calculate execution time using %%time
- Why is timeit() the best way to measure the execution time of Python code?
- Conclusion
- SOLVED: Measure Execution Time in Python [5 Methods]
- Introduction
- Method-1 : Use the python time library
- Method-2 : Use sleep timer to do complex computations
- Method-3 : Use time.time_ns() to get rid of rounding off errors
- Method-4 : CPU execution time
- Method-5 : Using datetime module
- What is the best way?
- Conclusion
- Further Reading
- Leave a Comment Cancel reply
- Python Tutorial
How to Get time of a Python program’s execution
In this article, we will learn to calculate the time taken by a program to execute in Python. We will use some built-in functions with some custom codes as well. Let’s first have a quick look over how the program’s execution affects the time in Python.
Programmers must have often suffered from «Time Limit Exceeded» error while building program scripts. In order to resolve this issue, we must optimize our programs to perform better. For that, we might need to know how much time the program is taking for its execution. Let us discuss different functions supported by Python to calculate the running time of a program in python.
The time of a Python program’s execution measure could be inconsistent depending on the following factors:
- The same program can be evaluated using different algorithms
- Running time varies between algorithms
- Running time varies between implementations
- Running time varies between computers
- Running time is not predictable based on small inputs
Calculate Execution Time using time() Function
We calculate the execution time of the program using time.time() function. It imports the time module which can be used to get the current time. The below example stores the starting time before the for loop executes, then it stores the ending time after the print line executes. The difference between the ending time and starting time will be the running time of the program. time.time() function is best used on *nix.
import time #starting time start = time.time() for i in range(3): print("Hello") # end time end = time.time() # total time taken print("Execution time of the program is- ", end-start)
Hello
Hello
Hello
Execution time of the program is- 1.430511474609375e-05
Calculate execution time using timeit() function
We calculate the execution time of the program using timeit() function. It imports the timeit module. The result is the execution time in seconds. This assumes that your program takes at least a tenth of a second to run.
The below example creates a variable and wraps the entire code including imports inside triple quotes. The test code acts as a string. Now, we call the time.timeit() function. The timeit() function accepts the test code as an argument, executes it, and records the execution time. The value of the number argument is set to 100 cycles.
import timeit test_code = """ a = range(100000) b = [] for i in a: b.append(i+2) """ total_time = timeit.timeit(test_code, number=200) print("Execution time of the program is-", total_time)
Execution time of the program is- 4.26646219700342
Calculate execution time using time.clock() Function
Another function of the time module to measure the time of a program’s execution is time.clock() function. time.clock() measures CPU time on Unix systems, not wall time. This function is mainly used for benchmarking purposes or timing algorithms. time.clock() may return slightly better accuracy than time.time() . It returns the processor time, which allows us to calculate only the time used by this process. It is best used on Windows.
import time t0= time.clock() print("Hello") t1 = time.clock() - t0 print("Time elapsed: ", t1 - t0) # CPU seconds elapsed (floating point)
Hello
Time elapsed: -0.02442
Note:
time.clock() is «Deprecated since version 3.3». The behavior of this function depends on the platform. Instead, we can use perf_counter() or process_time() depending on the requirements or have a well-defined behavior.
time.perf_counter() — It returns the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide.
time.process_time() — It returns the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep. For example,
start = time.process_time() . do something elapsed = (time.process_time() - start)
Calculate execution time using datetime.now() Function
We calculate the elapsed time using datetime.datetime.now() from the datetime module available in Python. It does not make the script a multi-line string like in timeit() . This solution is slower than the timeit() since calculating the difference in time is included in the execution time. The output is represented as days, hours, minutes, etc
The below example saves the current time before any execution in a variable. Then call datetime.datetime.now() after the program execution to find the difference between the end and start time of execution.
import datetime start = datetime.datetime.now() list1 = [4, 2, 3, 1, 5] list1.sort() end = datetime.datetime.now() print(end-start)
Calculate execution time using %%time
We use %%time command to calculate the time elapsed by the program. This command is basically for the users who are working on Jupyter Notebook. This will only capture the wall time of a particular cell.
%%time [ x**2 for x in range(10000)]
Why is timeit() the best way to measure the execution time of Python code?
1. You can also use time.clock() on Windows and time.time() on Mac or Linux. However, timeit() will automatically use either time.clock() or time.time() in the background depending on the operating system.
2. timeit() disables the garbage collector which could otherwise skew the results.
3. timeit() repeats the test many times to minimize the influence of other tasks running on your operating system.
Conclusion
In this article, we learned to calculate the time of execution of any program by using functions such as time() , clock() , timeit() , %%time etc. We also discussed the optimization of the python script. We learned about various functions and their uniqueness.
SOLVED: Measure Execution Time in Python [5 Methods]
This article is about python time start time stop execution. Many different techniques are used to get the start time and stop time of a python script.
Introduction
Measuring python time start time stop is very important, since in many algorithms, time needs to be calculated and compared and the fastest one is usually selected. There is no function or library in python that directly so in this article we will see how we can achieve the execution time using different techniques.
Method-1 : Use the python time library
One way to find python time start time stop is to use the time library declare two variables and subtract the start time from end time, this will be the final time.
import time import random start=time.time() for i in range(1,1000000): a=random.randint(1,1000000) b=random.randint(1,1000000) c=a+b end=time.time() print("the time is " + str(end-start)+ " seconds")
the time is 2.265195369720459 seconds
Method-2 : Use sleep timer to do complex computations
If you are doing complex computation, you can use the sleep function to make the main thread sleep, in the meantime the computation can be done and after that , the execution time will be the same as the sleep time , code for this is
import time def complexCompute(n): for i in range(n): for j in range(n): for k in range(n): pass def main(): for i in range(10): complexCompute(10) time.sleep(0.02) print("code time is <>".format(time.time())) if __name__ == '__main__': main()
code time is 1660055052.451363 code time is 1660055052.4840262 code time is 1660055052.5157845 code time is 1660055052.5469954 code time is 1660055052.5787077 code time is 1660055052.6094527 code time is 1660055052.6407127 code time is 1660055052.6728058 code time is 1660055052.703756 code time is 1660055052.7342584
While using time.time() , keep in mind that the time is shown in floating point numbers, which may be confusing at times.
Method-3 : Use time.time_ns() to get rid of rounding off errors
The logic behind the code is similar to the first way that we studied, but to get accurate and more readable results, we use time_ns(). If I write the same code as above but use time_ns() compare the outputs.
# python time start time stop import time import random # python time start start=time.time_ns() for i in range(1,1000000): a=random.randint(1,1000000) b=random.randint(1,1000000) c=a+b end=time.time_ns() # print python time start time stop print("the time taken for script execution is " + str(end-start)+ " nano seconds")
The output of this code is :
the time taken for script execution is 2321635400 nano seconds
Method-4 : CPU execution time
CPU execution time can be used to calculate the python time start time stop . the code is following
# python time start time stop start_time_ns = time.process_time_ns() # random computation end_time_ns = time.process_time_ns() print ("Time taken for script execution:", end_time_ns - start_time_ns)
Method-5 : Using datetime module
We can also use python datetime module to get the script execution time:
import time import random from datetime import timedelta start_time = time.monotonic() for i in range(1,1000000): a=random.randint(1,1000000) b=random.randint(1,1000000) c=a+b end_time = time.monotonic() # Calculate execution time print(timedelta(seconds=end_time - start_time))
What is the best way?
To compare all of the ways to calculate execution time, almost all of them are almost similar but in some cases, for example if we make the main thread sleep for some time, and the computation completes before that time, the execution time that is extended is useless. In the time.time.now() method, it is not easy to read time in floating points, thus the nano-seconds technique can be best to calculate python time start stop time. Although in some cases the sleep method can be helpful, when complex computations are long and need more time for execution.
Conclusion
There are different ways to calculate the python time start time stop we studied four ways, one is to measure the start time and then the stop time and subtracting both, second is using sleep method so that main thread wait for the complex computations. Other than that, cpu execution time or time in nano seconds can be used to calculate python time start time stop.
Further Reading
Related Keywords: python timeit, python time function runtime, python execution time in minutes, python time elapsed, python measure execution time of code block, python time sleep, python calculate execution time in seconds, python execution time in milliseconds, python measure execution time, running time python, python running time, python time execution, python timing execution, python execution time
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Leave a Comment Cancel reply
Python Tutorial
- Python Multiline Comments
- Python Line Continuation
- Python Data Types
- Python Numbers
- Python List
- Python Tuple
- Python Set
- Python Dictionary
- Python Nested Dictionary
- Python List Comprehension
- Python List vs Set vs Tuple vs Dictionary
- Python if else
- Python for loop
- Python while loop
- Python try except
- Python try catch
- Python switch case
- Python Ternary Operator
- Python pass statement
- Python break statement
- Python continue statement
- Python pass Vs break Vs continue statement
- Python function
- Python call function
- Python argparse
- Python *args and **kwargs
- Python lambda function
- Python Anonymous Function
- Python optional arguments
- Python return multiple values
- Python print variable
- Python global variable
- Python copy
- Python counter
- Python datetime
- Python logging
- Python requests
- Python struct
- Python subprocess
- Python pwd
- Python UUID
- Python read CSV
- Python write to file
- Python delete file
- Python any() function
- Python casefold() function
- Python ceil() function
- Python enumerate() function
- Python filter() function
- Python floor() function
- Python len() function
- Python input() function
- Python map() function
- Python pop() function
- Python pow() function
- Python range() function
- Python reversed() function
- Python round() function
- Python sort() function
- Python strip() function
- Python super() function
- Python zip function
- Python class method
- Python os.path.join() method
- Python set.add() method
- Python set.intersection() method
- Python set.difference() method
- Python string.startswith() method
- Python static method
- Python writelines() method
- Python exit() method
- Python list.extend() method
- Python append() vs extend() in list
- Create your first Python Web App
- Flask Templates with Jinja2
- Flask with Gunicorn and Nginx
- Flask SQLAlchemy