Python | time.monotonic_ns() method
Last Updated :
08 Dec, 2022
Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules. time.monotonic_ns() method of time module in Python is used to get the value of a monotonic clock in nanoseconds. This method is similar to time.monotonic() method which returns the monotonic clock value in fractional seconds. A monotonic clock is a clock that can not go backwards.
Syntax: time.monotonic_ns() Parameter: No parameter is required. Return type: This method returns an integer value which represents the value of a monotonic clock in nanoseconds.
Code #1: Use of time.monotonic_ns() method to get value of a monotonic clock in nanoseconds
Python3
import time
value1 = time.monotonic()
value2 = time.monotonic_ns()
print ("Value of the monotonic clock ( in fractional seconds):", value1)
print ("Value of the monotonic clock ( in nanoseconds):", value2)
|
Output:
Value of the monotonic clock (in fractional seconds): 13486.679399824
Value of the monotonic clock (in nanoseconds): 13486679402777
Code #2: Use of time.monotonic_ns() method to measure elapsed time in long running process.
Python3
import time
def factorial(n):
f = 1
for i in range (n, 1 , - 1 ):
f = f * i
return f
start = time.monotonic_ns()
print ("At the beginning of the process")
print ("Value of the monotonic clock ( in nanoseconds):", start, "\n")
i = 0
fact = [ 0 ] * 10 ;
while i < 10 :
fact[i] = factorial(i)
i = i + 1
for i in range ( 0 , len (fact)):
print ("Factorial of % d:" % i, fact[i])
end = time.monotonic_ns()
print ("\nAt the end of the process")
print ("Value of the monotonic clock ( in nanoseconds):", end)
print ("Time elapsed during the process:", end - start)
|
Output:
At the beginning of the process
Value of the monotonic clock (in nanoseconds): 14671301967243
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 process
Value of the monotonic clock (in nanoseconds): 14671302231487
Time elapsed during the process: 264244
Reference: https://docs.python.org/3/library/time.html#time.monotonic_ns
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...