Commit 5a58eaa7

5a58eaa7dd6fMerged

Richard Ramsden <[email protected]> · 6 months ago · 1 file · ~1 modified

Description

Special-case Time.now.to_i to skip the float roundtrip

Going through (mrb_int)((double)tv_sec + tv_nsec/1e9) rounds up to tv_sec+1 when tv_nsec lands in the last ~240ns of a second (double-precision spacing at ~1.7e9 is ~4.77e-7), so Time.now.to_i could disagree with CRuby ~1 in 4M calls.

Detect Time.now.to_i at the call dispatch entry and emit ((mrb_int)time(NULL)) directly, matching CRuby's exact tv_sec semantics. Time.now.to_f and bare Time.now still go through clock_gettime for sub-second precision.

Verified by inspecting the emitted C for both forms.

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

Details

Commit
5a58eaa7dd6f
Parent
c41e250d3235

spinel_codegen.rbmodifiedView file

@@ -16607,6 +16607,18 @@
1660716607 end
1660816608 end
1660916609
16610+ # Time.now.to_i — bypass the Time.now float roundtrip and emit
16611+ # time(NULL) directly. Going through (mrb_int)((double)tv_sec +
16612+ # tv_nsec/1e9) rounds up to tv_sec+1 when tv_nsec lands in the
16613+ # last ~240ns of a second (~2.4e-7 chance per call); time(NULL)
16614+ # returns exact tv_sec, matching CRuby's Time#to_i semantics.
16615+ if mname == "to_i" && recv >= 0 && @nd_type[recv] == "CallNode" && @nd_name[recv] == "now"
16616+ rr = @nd_receiver[recv]
16617+ if rr >= 0 && @nd_type[rr] == "ConstantReadNode" && @nd_name[rr] == "Time"
16618+ return "((mrb_int)time(NULL))"
16619+ end
16620+ end
16621+
1661016622 recv_type = infer_type(recv)
1661116623 # Nullable receiver: dispatch identically to the base type. The
1661216624 # null check is the caller's responsibility, matching Ruby's