Python | time.monotonic_ns () method

Python Methods and Functions

time.monotonic_ns() time unit in Python is used to get the monotonic clock value in nanoseconds. This method is similar to

# Python program to explain the time.monotonic_ns () method

  
# time module import

import time

 
# Get value
# monotone th hours in
# fractions of a second using
# time.monotonic () method

value1 = time.monotonic ()

 
# Get value
# monotonic hours in
# nanoseconds using
# time.monotonic_ns () method

value2 = time.monotonic_ns ()

 
# output the value
# monotonous hours (in fractions of a second)

print ( "Value of the monotonic clock (in fractional seconds):" , value1)

 
# output the value
# monotonic hours (in nanoseconds)

print ( " Value of the monotonic clock (in nanoseconds): " , value2)

Exit:

 Value of the monotonic clock (in fractional seconds) : 13486.679399824 Value of the monotonic clock (in nanoseconds): 13486679402777 

Code # 2: Using the method time.monotonic_ns () to measure elapsed time in a long process.

# Python program to explain the time.monotonic_ns () method

 < br /> # time module import

import time

 

 
# Function for calculating the factorial
No. of this number

def factorial (n):

f = 1

for i in range (n, 1 , - 1 ):

  f = f * i

 

return

 

 
# Get the value
# monotonous hours in nanoseconds per
# starting the process
# using the time.monotonic_ns () method

start = time.monotonic_ns ()

 
# output the value
# monotonous hours in nanoseconds

print ( " At the beginning of the process " )

print ( "Value of the monotonic clock (in nanoseconds):" , start, "" )

 
# Calculate factorial of total
# numbers from 0 to 9

i = 0

fact = [ 0 ] * 10

 

while i & lt;  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
# monotonous hours in nanoseconds
# using the time.monotonic_ns () method

end = time.monotonic_ns ()

  
# output the value
# monotonous hours

print ( "At the end of the process" )

print ( "Value of the monotonic clock (in nanoseconds):" , end)

print ( "T ime elapsed during the process: " , end - start) 

Exit:

 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 

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





Get Solution for free from DataCamp guru