Cross platform time calculation

Question:

try:       
   Start = time.clock() # best method to measure time on windows
except: 
   Start = time.time() # cross platform time

main() # code to measure time of


try: 
   End = time.clock() # for windows
except: 
   End = time.time() # cross platform     

I am attempting to calculate the time it takes for my program to execute. I have heard that time.clock() is the best method to calculate time on windows, but have heard that it is not cross platform, which is why I have added time.time() as the exception. Will this work as intended on cross platforms? That is using time.clock() if possible, else reverting to time.time(). Is there a better method to accomplish this? Thank you

Asked By: Justin Fairbanks

||

Answers:

In Python 3.3 and later versions, time.clock() has been deprecated and replaced with time.process_time(). Therefore, it’s better to use time.process_time() instead of time.clock() on newer versions of Python. For earlier versions of Python, you can use time.perf_counter() instead of time.clock().

To measure the execution time of a block of code, it’s also recommended to use the "with" statement in combination with timeit.default_timer(). The "with" statement ensures that the timer is only started and stopped around the block of code being measured, and not during any setup or cleanup code.

Here’s an example implementation that will work on all platforms:

import timeit

start = timeit.default_timer()
main() # code to measure time of
end = timeit.default_timer()
print('Execution time:', end - start)
Answered By: Dayamoy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.