Sometimes, we need to evaluate the performance of a python script, we have to calculate the run or execution time a python program. In this tutorial, we will introduce you some ways.
In order to get the time spent by python script, you should get the end time and the start time.
Method 1: Use python datetime model
Here is an example:
import datetime import time starttime = datetime.datetime.now() #long running for i in range(3): time.sleep(1) endtime = datetime.datetime.now() t = (endtime - starttime).seconds print(t)
Run this code, we will find this python script takes 3 seconds.
However, you should notice: if the time spent is less than 1 senconds, you will get o sencond.
Method 2: Use python time.time() function
Here is an example:
import time starttime = time.time() #long running for i in range(3): time.sleep(0.1) endtime = time.time() t = endtime - starttime print(t)
Run this code, you may get 0.31941890716552734 seconds.
Method 3: Use python time.clock() function
Here is an example:
import time starttime = time.clock() #long running for i in range(3): time.sleep(0.1) endtime = time.clock() t = endtime - starttime print(t)
Run this code, you may get 0.3198977 seconds.
The differences among these three methods
The datetime and time.time() will calculate the cpu time spent by other applications. However, time.clock() only calculate the time spent by this python script.