當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python time.clock()用法及代碼示例


Python中的時間模塊提供了各種與時間相關的函數。

time.clock()Python中的時間模塊方法用於獲取當前處理器時間,以秒為單位的浮點數。 As,在時間模塊中定義的大多數函數都調用相應的C庫函數。time.clock()方法還調用相同名稱的C庫函數以獲取結果。返回的浮點值的精度取決於所調用的C庫函數。

注意:從Python 3.3版開始不推薦使用此方法,在3.8版中將刪除該方法。此方法的行為取決於平台。


用法: time.clock()

參數:不需要任何參數。

返回類型:此方法返回一個浮點值,該值代表以秒為單位的當前處理器時間。

代碼1:用於time.clock()獲取當前處理器時間的方法

# Python program to explain time.clock() method 
  
# importing time module 
import time 
  
# Get the current processor 
# time in seconds 
pro_time = time.clock() 
  
# print the current  
# processor time 
print("Current processor time (in seconds):", pro_time)
輸出:
Current processor time (in seconds): 0.042379

代碼2:用於time.clock()獲取當前處理器時間的方法

# Python program to explain time.clock() method  
  
# importing time module  
import time  
  
  
# Function to calculate factorial  
# of the given number  
def factorial(n):  
    f = 1
    for i in range(n, 1, -1):  
        f = f * i  
      
    return f  
  
  
# Get the current processor time 
# in seconds at the  
# beginning of the calculation  
# using time.clock() method  
start = time.clock()  
  
# print the processor time in seconds  
print("At the beginning of the calculation")  
print("Processor time (in seconds):", start, "\n")  
  
  
# Calculate factorial of all  
# numbers form 0 to 9  
i = 0
fact = [0] * 10;  
  
while i < 10:  
    fact[i] = factorial(i)  
    i = i + 1
  
# Print the calculated factorial  
for i in range(0, len(fact)):  
    print("Factorial of % d:" % i, fact[i])  
  
# Get the processor time 
# in seconds at the end  
# of the calculation  
# using time.clock() method  
end = time.clock()  
  
print("\nAt the end of the calculation")  
print("Processor time (in seconds):", end)  
print("Time elapsed during the calculation:", end - start)     
輸出:
At the beginning of the calculation
Processor time (in seconds): 0.03451 

Factorial of  0: 1
Factorial of  1: 1
Factorial of  2: 2
Factorial of  3: 6
Factorial of  4: 24
Factorial of  5: 120
Factorial of  6: 720
Factorial of  7: 5040
Factorial of  8: 40320
Factorial of  9: 362880

At the end of the calculation
Processor time (in seconds): 0.034715
Time elapsed during the calculation: 0.0002050000000000038

參考: https://docs.python.org/3/library/time.html#time.clock



相關用法


注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | time.clock() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。