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:

Ruby
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

Similar Reads

Using Benchmark.realtime

Benchmark.realtime method to measure the time taken for the operation inside the block. Inside the block, we perform the operation we want to do. This method returns the time taken in seconds. We multiply it by 1000 to convert it into milliseconds....

Using Process.clock_gettime

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....

Using Time class

This approach is similar to the previous aprroach. In Time class method we have Time.now method using which we can calculate the current time before performing the operation and after performing the operation. Then we calculate the difference between them. It returns the result in seconds. We multiply it by 1000 to convert into milliseconds....