Skip to content

Instantly share code, notes, and snippets.

@ibanez270dx
Last active September 8, 2018 20:54
Show Gist options
  • Save ibanez270dx/6a772f8a38420ab0d22012233930df72 to your computer and use it in GitHub Desktop.
Save ibanez270dx/6a772f8a38420ab0d22012233930df72 to your computer and use it in GitHub Desktop.
Return time taken in milliseconds to process a block of code, along with its result.
module Benchmark
# Similar to Benchmark.realtime, but returns the result of the block along with time taken in milliseconds.
# Ex: Benchmark.perform{ sleep(3); "hello" } => [3003.2030000002123, "hello"]
#
# Benchmark.realtime | https://ruby-doc.org/stdlib-2.5.0/libdoc/benchmark/rdoc/Benchmark.html#method-c-realtime
# Process.clock_gettime | http://ruby-doc.org/core-2.5.0/Process.html#method-c-clock_gettime
def self.perform
t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
result = yield
[(Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0) * 1000, result]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment