Skip to content

fix: measure does not measure when an exception occurs - #1247

Merged
tompng merged 1 commit into
ruby:masterfrom
GabrielLidenor:fix-measure-in-exception
Sep 7, 2026
Merged

fix: measure does not measure when an exception occurs#1247
tompng merged 1 commit into
ruby:masterfrom
GabrielLidenor:fix-measure-in-exception

Conversation

@GabrielLidenor

Copy link
Copy Markdown
Contributor

closes #533

Why

The failure occurred because an exception raised by result = block.() stopped normal execution before the elapsed time could be calculated and displayed.

Wrapping the evaluation in begin...ensure guarantees that the timing code runs even when the evaluated block raises an exception. The original exception is still propagated and handled normally afterward.

Proof

 irb git:(fix-measure-in-exception) bundle exec ruby -Ilib exe/irb

⢀⡴⠊⢉⡟⢿  IRB v1.18.0 - Ruby 4.0.1
⣎⣀⣴⡋⡟⣻  "show_doc method" to view documentation
⣟⣼⣱⣽⣟⣾  ~/Projects/irb

irb(main):001> measure
TIME is added.
irb(main):002> Regexp.compile('^a*b?a*()\1$', timeout: 10.0) =~ "a" * 50000 + "x"
processing time: 10.000346s
(irb):2:in '<main>': regexp match timeout (Regexp::TimeoutError)
	from exe/irb:9:in '<main>'
irb(main):003>

The reason it was failing it was because when an exception ocurred the
code stop in  result = block.() preventing the lines to display time to
be executed.

The begin, ensure forces the code to execute the other lines after the
excception

@tompng tompng left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. Thank you!

Just one note:
Calling Kernel.exit will also print processing time, but it won't be a problem.

irb(main):001> measure
TIME is added.
irb(main):002> Kernel.exit
processing time: 0.000079s

IRB's exit command won't print it.

@tompng
tompng merged commit 44c2b15 into ruby:master Sep 7, 2026
40 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

measure does not measure when an exception occurs

2 participants