From 13e2ce42494ca3a401cafc8b6fde09d8ded8e659 Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Thu, 27 Nov 2025 08:17:17 +0900 Subject: [PATCH] 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 --- mrbgems/mruby-benchmark/mrbgem.rake | 2 ++ mrbgems/mruby-benchmark/mrblib/benchmark.rb | 22 +++++++++++++-------- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/mrbgems/mruby-benchmark/mrbgem.rake b/mrbgems/mruby-benchmark/mrbgem.rake index 707080e1d..56cfc6b16 100644 --- a/mrbgems/mruby-benchmark/mrbgem.rake +++ b/mrbgems/mruby-benchmark/mrbgem.rake @@ -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 diff --git a/mrbgems/mruby-benchmark/mrblib/benchmark.rb b/mrbgems/mruby-benchmark/mrblib/benchmark.rb index 0889c22fb..bee9a9084 100644 --- a/mrbgems/mruby-benchmark/mrblib/benchmark.rb +++ b/mrbgems/mruby-benchmark/mrblib/benchmark.rb @@ -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