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


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


Python中的時間模塊提供了各種與時間相關的函數。該模塊屬於Python的標準實用程序模塊。

time.monotonic_ns()Python中的時間模塊方法用於獲取單調時鍾的值(以納秒為單位)。此方法類似於time.monotonic()方法,該方法以小數秒為單位返回單調時鍾值。單調時鍾是不能向後移動的時鍾。

用法: time.monotonic_ns()

參數:不需要任何參數。

返回類型:此方法返回一個整數值,該整數值表示單調時鍾的值(以納秒為單位)。

代碼1:用於time.monotonic_ns()一種以納秒為單位獲取單調時鍾值的方法

# Python program to explain time.monotonic_ns() method 
  
# importing time module 
import time 
  
# Get the value of 
# the monotonic clock in  
# fractional seconds using 
# time.monotonic() method 
value1 = time.monotonic() 
  
# Get the value of 
# the monotonic clock in  
# nanoseconds using 
# time.monotonic_ns() method 
value2 = time.monotonic_ns() 
  
# print the value of  
# the monotonic clock (in fractional seconds) 
print("Value of the monotonic clock (in fractional seconds):", value1) 
  
# print the value of  
# the monotonic clock (in nanoseconds) 
print("Value of the monotonic clock (in nanoseconds):", value2)
輸出:
Value of the monotonic clock (in fractional seconds): 13486.679399824
Value of the monotonic clock (in nanoseconds): 13486679402777

代碼2:用於time.monotonic_ns()在長時間運行過程中測量經過時間的方法。

# Python program to explain time.monotonic_ns() 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 value of the 
# monotonic clock in nanoseconds at the  
# beginning of the process 
# using time.monotonic_ns() method 
start = time.monotonic_ns() 
  
# print the value of  
# the monotonic clock in nanoseconds 
print("At the beginning of the process") 
print("Value of the monotonic clock (in nanoseconds):", 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("Factorail of % d:" % i, fact[i]) 
  
# Get the value of 
# monotonic clock in nanoseconds 
# using time.monotonic_ns() method 
end = time.monotonic_ns() 
  
# print the value of  
# the monotonic clock 
print("\nAt the end of the process") 
print("Value of the monotonic clock (in nanoseconds):", end) 
print("Time elapsed during the process:", end - start)    
輸出:
At the beginning of the process
Value of the monotonic clock (in nanoseconds): 14671301967243 

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

At the end of the process
Value of the monotonic clock (in nanoseconds): 14671302231487
Time elapsed during the process: 264244

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



相關用法


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