[ruby/openssl] test/openssl/test_ossl.rb: use clock_gettime for measuring time

The benchmark library is planned to become a bundled gem in Ruby 3.5.
While we can add it in our Gemfile, it is only used in
test_memcmp_timing and the usage can be easily replaced with a few
Process.clock_gettime calls.

https://github.com/ruby/openssl/commit/9a746ed1a4
This commit is contained in:
Kazuki Yamaguchi 2025-01-30 00:07:07 +09:00 committed by git
parent d3bb42776c
commit 81c83fd79f

View File

@ -42,12 +42,6 @@ class OpenSSL::OSSL < OpenSSL::SSLTestCase
end
def test_memcmp_timing
begin
require "benchmark"
rescue LoadError
pend "Benchmark is not available in this environment. Please install it with `gem install benchmark`."
end
# Ensure using fixed_length_secure_compare takes almost exactly the same amount of time to compare two different strings.
# Regular string comparison will short-circuit on the first non-matching character, failing this test.
# NOTE: this test may be susceptible to noise if the system running the tests is otherwise under load.
@ -58,8 +52,14 @@ class OpenSSL::OSSL < OpenSSL::SSLTestCase
a_b_time = a_c_time = 0
100.times do
a_b_time += Benchmark.measure { 100.times { OpenSSL.fixed_length_secure_compare(a, b) } }.real
a_c_time += Benchmark.measure { 100.times { OpenSSL.fixed_length_secure_compare(a, c) } }.real
t1 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
100.times { OpenSSL.fixed_length_secure_compare(a, b) }
t2 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
100.times { OpenSSL.fixed_length_secure_compare(a, c) }
t3 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
a_b_time += t2 - t1
a_c_time += t3 - t2
end
assert_operator(a_b_time, :<, a_c_time * 10, "fixed_length_secure_compare timing test failed")
assert_operator(a_c_time, :<, a_b_time * 10, "fixed_length_secure_compare timing test failed")