How to use Process.clock_gettime In Ruby
Process.clock_gettime calculates the difference between start time and end time. It records the current time before performing the operation and after performing the operation using Process.clock_gettime(Process::CLOCK_MONOTIC) . This method returns the time taken in seconds. We multiply it by 1000 to convert into milliseconds.
Syntax:
start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
#operation
end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
time_in_seconds = end_time – start_time
Below is the Ruby program to convert into milliseconds using Process.clock_gettime:
start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
# Your operation goes here
# For example:
sleep(0.5) # Simulating an operation that takes 0.5 seconds
end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
#calculating the difference
time_in_seconds = end_time - start_time
#converting seconds into milliseconds
time_in_milliseconds = time_in_seconds * 1000.0
puts "Time taken: #{time_in_milliseconds} milliseconds"
Output
Time taken: 500.56117499980246 milliseconds
How to time an operation in milliseconds in Ruby?
In this article, we will learn about how to time an operation in milliseconds in Ruby. We can perform this using different approaches.
Table of Content
- Using Benchmark.realtime
- Using Process.clock_gettime
- Using Time class