mruby-benchmark: fix implementation for mruby environment

fix implementation to work correctly in mruby:
- use String#% instead of sprintf for formatting
- use $stdout directly for output instead of bare print/puts
- add nil check for $stdout to handle test environments
- use Object.const_defined? instead of defined? keyword
- create new Tms instance with label instead of instance_variable_set
- add dependencies: mruby-sprintf and mruby-io

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Yukihiro "Matz" Matsumoto
2025-11-27 08:17:17 +09:00
parent 2f40f3d170
commit 13e2ce4249
2 changed files with 16 additions and 8 deletions
+2
View File
@@ -5,4 +5,6 @@ MRuby::Gem::Specification.new('mruby-benchmark') do |spec|
spec.add_dependency('mruby-time', :core => 'mruby-time')
spec.add_dependency('mruby-objectspace', :core => 'mruby-objectspace')
spec.add_dependency('mruby-sprintf', :core => 'mruby-sprintf')
spec.add_dependency('mruby-io', :core => 'mruby-io')
end
+14 -8
View File
@@ -20,7 +20,7 @@ module Benchmark
end
def to_s
format("%10.6f %10.6f %10.6f (%10.6f)\n", @utime, @stime, total, @real)
"%10.6f %10.6f %10.6f (%10.6f)\n" % [@utime, @stime, total, @real]
end
def format(format_str)
@@ -45,15 +45,19 @@ module Benchmark
def report(label = "")
tms = Benchmark.measure { yield }
tms.instance_variable_set(:@label, label)
# Create new Tms with label set
tms = Benchmark::Tms.new(tms.utime, tms.stime, tms.cutime, tms.cstime,
tms.real, label, tms.objects, tms.memory)
label_str = label.to_s
if label_str.length < @width
label_str = label_str + " " * (@width - label_str.length)
end
print label_str
print tms.to_s
if $stdout
$stdout.print label_str
$stdout.print tms.to_s
end
@results << tms
tms
@@ -71,7 +75,7 @@ module Benchmark
start_count = nil
if memory
if defined?(ObjectSpace)
if Object.const_defined?(:ObjectSpace)
start_count = ObjectSpace.count_objects
start_objects = start_count.values.inject(0) { |sum, n| sum + n }
end
@@ -113,10 +117,12 @@ module Benchmark
report = Report.new(label_width)
# Print header
if label_width > 0
print " " * label_width
if $stdout
if label_width > 0
$stdout.print " " * label_width
end
$stdout.puts " user system total real"
end
puts " user system total real"
yield report