Python 計算程序運行時間,首先需要導入 time 模塊。
關於 time 模塊 :
序號 | 函數及描述 | 實例 |
---|---|---|
1 | time.altzone 返回格林威治西部的夏令時地區的偏移秒數。如果該地區在格林威治東部會返回負值(如西歐,包括英國)。對夏令時啟用地區才能使用。 |
>>> import time >>> print ("time.altzone %d " % time.altzone) time.altzone -28800 |
2 | time.asctime([tupletime]) 接受時間元組並返回一個可讀的形式為"Tue Dec 11 18:07:14 2008"(2008年12月11日 周二18時07分14秒)的24個字符的字符串。 |
>>> import time >>> t = time.localtime() >>> print ("time.asctime(t): %s " % time.asctime(t)) time.asctime(t): Thu Apr 7 10:36:20 2016 |
3 | time.clock() 用以浮點數計算的秒數返回當前的CPU時間。用來衡量不同程序的耗時,比time.time()更有用。 |
|
4 | time.ctime([secs]) 作用相當於asctime(localtime(secs)),未給參數相當於asctime() |
>>> import time >>> print ("time.ctime() : %s" % time.ctime()) time.ctime() : Thu Apr 7 10:51:58 2016 |
5 | time.gmtime([secs]) 接收時間輟(1970紀元后經過的浮點秒數)並返回格林威治天文時間下的時間元組t。注:t.tm_isdst始終為0 |
>>> import time >>> print ("gmtime :", time.gmtime(1455508609.34375)) gmtime : time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15, |
6 | time.localtime([secs] 接收時間輟(1970紀元后經過的浮點秒數)並返回當地時間下的時間元組t(t.tm_isdst可取0或1,取決於當地當時是不是夏令時)。 |
>>> import time >>> print ("localtime(): ", time.localtime(1455508609.34375)) localtime(): time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15, |
7 | time.mktime(tupletime) 接受時間元組並返回時間輟(1970紀元后經過的浮點秒數)。 |
|
8 | time.sleep(secs) 推遲調用線程的運行,secs指秒數。 |
#!/usr/bin/python3 import time print ("Start : %s" % time.ctime()) time.sleep( 5 ) print ("End : %s" % time.ctime()) |
9 | time.strftime(fmt[,tupletime]) 接收以時間元組,並返回以可讀字符串表示的當地時間,格式由fmt決定。 |
>>> import time >>> print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) 2016-04-07 11:18:05 |
10 | time.strptime(str,fmt='%a %b %d %H:%M:%S %Y') 根據fmt的格式把一個時間字符串解析為時間元組。 |
>>> import time >>> struct_time = time.strptime("30 Nov 00", "%d %b %y") >>> print ("返回元組: ", struct_time) 返回元組: time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, |
11 | time.time( ) 返回當前時間的時間戳(1970紀元后經過的浮點秒數)。 |
>>> import time >>> print(time.time()) 1459999336.1963577 |
12 | time.tzset() 根據環境變量TZ重新初始化時間相關設置。 |
計算程序運行時間:
方法①:time.clock() (此處已試過,換成time.time() 也是可以正確得出計時結果的)
import time def start_sleep(): time.sleep(3) if __name__ == '__main__': #The start time start = time.clock() #A program which will run for 3 seconds start_sleep() #The End time end = time.clock() print("The function run time is : %.03f seconds" %(end-start)) # 輸出 :The function run time is : 2.999 seconds
方法②:使用 time.clock(),只有第一個計時輸出有結果(格式化不了??);若使用time.time() 則全部無結果。
#----Simple Calculate Runtime----- import time start = time.clock() sum=0 for i in range(1,101): sum=sum+i print("The Result Sum is :",sum) end = time.clock() c=end-start print("Runtime is :",c) ### 只有這個能算出計時結果!!! print("Format Runtime is :%0.2f s"%c ) print('Format Runtime is:{0:.3f}s'.format(c)) print("程序運行總耗時:%0.2f"%c, 's') print("The function run time is : %.02f seconds" %c)
輸出結果為: