Appearance
How do I get time of a Python program's execution?
To get the time it takes for a Python program to execute, you can use the time module. Here is an example of how you can use it:
Get the time it takes for a Python program to execute
python
import time
start_time = time.perf_counter()
for _ in range(1000000):
pass
end_time = time.perf_counter()
time_elapsed = end_time - start_time
print("Time taken: ", time_elapsed)
<div class="alert alert-info flex not-prose">Watch a video course Python - The Practical Guide
</div>
The time_elapsed variable will contain the time in seconds it took for the code to execute. Note that time.perf_counter() is used instead of time.time() because it provides higher precision and is not affected by system clock updates, making it the standard choice for measuring execution time. If you want the time in a more readable format, you can use the datetime module to convert the elapsed time to hours, minutes, and seconds.
Get the time it takes for a Python program to execute in a more readable format
python
import time
import datetime
start_time = time.perf_counter()
for _ in range(1000000):
pass
end_time = time.perf_counter()
time_elapsed = end_time - start_time
print("Time taken: ", time_elapsed)
print(datetime.timedelta(seconds=time_elapsed))This will print the time taken in a more readable format, such as 0:00:00.123456.