Some times you want to
calculate total elapased time for your program (or) a particular method. Common
mistake coders do while calculating method execution time is by using ‘time.time()’.
import time def processData(): sum=0 for i in range(100000000): sum*=i if __name__=="__main__": startTime=time.time() processData() endTime=time.time() print("Total time taken is", (endTime-startTime))
Output
Total time taken is
5.8600099086761475
One problem with time.time()
is it depends on system time. What if some body change the system time during
the execution of method, obviously you will get wrong results. So we require a
way to safely measure elapsed time in a program, that doesn’t depend on the
system time.
Better alternative is
to use time.monotonic() method (doesn’t depends on system clock), which return
the value (in fractional seconds) of a monotonic clock, i.e. a clock that
cannot go backwards.
import time def processData(): sum=0 for i in range(100000000): sum*=i if __name__=="__main__": startTime=time.monotonic() processData() endTime=time.monotonic() print("Total time taken is", (endTime-startTime))
Output
Total time taken is
5.917623278015526
No comments:
Post a Comment