lib/benchmark/perf/iteration.rb in benchmark-perf-0.5.0 vs lib/benchmark/perf/iteration.rb in benchmark-perf-0.6.0
- old
+ new
@@ -1,16 +1,17 @@
# frozen_string_literal: true
+require_relative "clock"
+require_relative "stats"
+require_relative "ips_result"
+
module Benchmark
module Perf
# Measure number of iterations a work could take in a second
#
# @api private
module Iteration
- MICROSECONDS_PER_SECOND = 1_000_000
- MICROSECONDS_PER_100MS = 100_000
-
# Call work by given times
#
# @param [Integer] times
# the times to call
#
@@ -28,19 +29,21 @@
module_function :call_times
# Calcualte the number of cycles needed for 100ms
#
# @param [Integer] iterations
- # @param [Float] elapsed_time
- # the total time for all iterations
+ # @param [Float] time_s
+ # the total time for all iterations in seconds
#
# @return [Integer]
# the cycles per 100ms
#
# @api private
- def cycles_per_100ms(iterations, elapsed_time)
- cycles = (iterations * (MICROSECONDS_PER_100MS / elapsed_time)).to_i
+ def cycles_per_100ms(iterations, time_s)
+ cycles = iterations * Clock::MICROSECONDS_PER_100MS
+ cycles /= time_s * Clock::MICROSECONDS_PER_SECOND
+ cycles = cycles.to_i
cycles <= 0 ? 1 : cycles
end
module_function :cycles_per_100ms
# Warmup run
@@ -49,53 +52,50 @@
# the number of seconds for warmup
#
# @api private
def run_warmup(warmup: 1, &work)
GC.start
- target = Perf.time_now + warmup
+
+ target = Clock.now + warmup
iter = 0
- elapsed_time = Perf.clock_time do
- while Perf.time_now < target
+ time_s = Clock.measure do
+ while Clock.now < target
call_times(1, &work)
iter += 1
end
end
- elapsed_time *= MICROSECONDS_PER_SECOND
- cycles_per_100ms(iter, elapsed_time)
+ cycles_per_100ms(iter, time_s)
end
module_function :run_warmup
# Run measurements
#
# @param [Numeric] time
- # the time to run measurements for
+ # the time to run measurements in seconds
+ # @param [Numeric] warmup
+ # the warmup time in seconds
#
# @api public
def run(time: 2, warmup: 1, &work)
- target = Time.now + time
- iter = 0
- measurements = []
- cycles = run_warmup(warmup: warmup, &work)
+ cycles_in_100ms = run_warmup(warmup: warmup, &work)
GC.start
- while Time.now < target
- bench_time = Perf.clock_time { call_times(cycles, &work) }
- next if bench_time <= 0.0 # Iteration took no time
- iter += cycles
- measurements << bench_time * MICROSECONDS_PER_SECOND
- end
+ result = IPSResult.new
- ips = measurements.map do |time_ms|
- (cycles / time_ms) * MICROSECONDS_PER_SECOND
- end
+ target = (before = Clock.now) + time
- final_time = Time.now
- elapsed_time = (final_time - target).abs
+ while Clock.now < target
+ time_s = Clock.measure { call_times(cycles_in_100ms, &work) }
- [Perf.average(ips).round, Perf.std_dev(ips).round, iter, elapsed_time]
+ next if time_s <= 0.0 # Iteration took no time
+
+ result.add(time_s, cycles_in_100ms)
+ end
+
+ result
end
module_function :run
end # Iteration
end # Perf
end # Benchmark