Construct TimeDuration from an integer without converting through double
Categories
(Core :: mozglue, task)
Tracking
()
| Tracking | Status | |
|---|---|---|
| firefox162 | --- | fixed |
People
(Reporter: jlink, Assigned: jlink)
References
(Blocks 1 open bug)
Details
(Keywords: perf-alert, Whiteboard: [fxpe])
Attachments
(3 external files)
TimeDuration stores its value as an integer count of platform ticks, but the only way to build one from a constant was FromMilliseconds() and its siblings, which take a double. That costs an integer-to-floating-point conversion, a multiply in floating point, range checks against the ends of int64_t, and checks for the infinities. It also costs a call that cannot be inlined, because BaseTimeDurationPlatformUtils::TicksFromMilliseconds is MFBT_API (a DLL import on Windows), and that also stops the compiler from folding a constant duration at compile time.
Three patches.
The first adds overloads of FromSeconds, FromMilliseconds and FromMicroseconds constrained to integral types, plus a new FromNanoseconds. Overload resolution prefers these for any integral argument, since an identity conversion beats the floating-integral conversion the double overloads need, so existing call sites that already pass an integer move to the integer path without being edited. Call sites passing a floating-point value keep the existing behavior.
From the platform's tick rate, the patch works out exactly how many ticks make up each unit: an exact rational reduced to lowest terms, plus the same value as a plain integer for units the tick rate divides evenly. Every tick rate we know of divides seconds, milliseconds and microseconds evenly, so those reduce to a single multiply with an overflow check. Microsoft documents that the QueryPerformanceCounter frequency is not derived from the hardware frequency and must not be assumed, so the rational is kept to handle the remaining cases exactly and cheaply. Where the tick is always a nanosecond these counts are compile-time constants, and a duration built from an integer constant folds away entirely.
The second updates call sites that already hold a whole number of units: explicit casts to double written only to satisfy the old signature, floating-point literals whose value is a whole number of the unit (using TimeDuration::Zero() where that number is zero), literals that are fractional in their unit but whole in a finer one, and constants declared double or float despite holding a whole number of units and only ever used as arguments to these factories. MainThreadIdlePeriod::GetLongIdlePeriod() now returns int32_t rather than float, since it handed one of those constants back out.
Two call sites change behavior rather than just cost. The atomic.wait timeout in WasmInstance.cpp arrives from the WebAssembly specification in nanoseconds and was converted with FromMicroseconds(double(timeout_ns) / 1000), a floating-point divide that rounds and discards sub-microsecond precision, and WebRenderLayerManager converted a display list build time the same way. FromNanoseconds does both exactly.
The third removes the places that took a TimeDuration apart into a double and rebuilt it, where duration arithmetic expresses the same thing directly: TimeoutManager::RunTimeout took a quarter of a budget via ToMilliseconds(), CCGCScheduler::ComputeMinimumBudgetForRunner scaled a budget by a double multiplier the same way, and MediaTimer<TimeStamp>::ArmTimer passed a TimeDuration it already held through FromMicroseconds(ToMicroseconds()), which truncated the delay to whole microseconds. That last one is a third, small behavior change.
A temporary diagnose_if on the four double overloads let the compiler enumerate every remaining call site in a Windows build, and platform-specific code elsewhere was checked separately. What's left takes a double for a reason (Web IDL and DOMHighResTimeStamp values, 1.0/fps and 1000.0/60.0 vsync intervals, playback-rate and animation-progress products, accumulated telemetry seconds), would need a pref type or API change to convert, or is TimeUnit::ToTimeDuration(), which is left to bug 2074335.
| Assignee | ||
Updated•1 month ago
|
| Assignee | ||
Comment 1•1 month ago
|
||
Here is a performance comparison of (a slightly earlier version of) this change. On Linux, calls to these functions simplify greatly (they almost disappear) so I believe that the Linux improvements shown in the comparison (specifically the ones to speedometer3, speedometer3-experimental and assorted-dom) are actually real. This should be a small win on other platforms but I don't expect them to be significant enough to actually show up anywhere.
| Assignee | ||
Comment 2•1 month ago
|
||
TimeDuration stores an integer count of platform ticks, but the only way to
build one from a count of units was FromMilliseconds() and its siblings, which
take a double. Passing an integer costs a round trip through floating point,
checks against the ends of int64_t and for the infinities, and a call to
MFBT_API TicksFromMilliseconds() that cannot be inlined, so a constant duration
cannot be folded either.
This adds integral overloads of FromSeconds, FromMilliseconds and
FromMicroseconds, plus a new FromNanoseconds. An identity conversion beats the
floating-integral conversion the double overloads need, so an integral argument
picks these with no call site edited, while a floating-point one behaves as
before.
How many ticks make up each unit is now computed from the platform's tick rate
rather than hidden inside a conversion function: an exact rational in lowest
terms, plus that value as a plain integer where it divides evenly. Every tick
rate we know of divides seconds, milliseconds and microseconds, so those need
one multiply and an overflow check; nanoseconds need the rational, as no rate
below 1 GHz divides them. Microsoft documents that the QueryPerformanceCounter
frequency must not be assumed, and its own example value does not divide
microseconds, so the rational covers such rates exactly rather than
approximately.
Where the tick rate is only known at run time (Windows, macOS) the conversion
stays out of line in TimeStamp.cpp, behind one entry point per unit so a call
site passes nothing but the count. TickScale, the reduction that builds it and
the scaling that consumes it are all private to that file, and the backends
hand over only a rate, so neither the tick rate nor the shape of the data
describing it is part of mozglue's ABI. Where the tick is always a nanosecond
the header holds four compile-time constants instead and the multiply is
inline, so a duration built from a constant folds to a single immediate.
The reduction is constexpr, so those rates - 10 MHz, 1 GHz, the Apple silicon
mach timebase, 19.2 MHz, Microsoft's example, and the ACPI PM timer - are
checked at compile time rather than by a runtime test.
An integer call site is smaller than the floating-point one it replaced, and
the conversion it calls does less work. Inlining the multiply at every call
site is faster still per call, but costs code at each of several hundred, so it
stays out of line.
These factories are kept out of hot paths, so no metric was expected to move,
though a try push does show indications of possible modest improvements to some
benchmarks on Linux. The other win is exactness - a value that was already an
integer no longer passes through double at all.
| Assignee | ||
Comment 3•1 month ago
|
||
Now that the From* factories have integer overloads, a caller holding an
integer count of units can pass it directly. Four kinds of site change here:
- Explicit casts to double, written only to satisfy the old signature.
- Floating-point literals whose value is a whole number of the unit, which
chose the double overload purely because of how the literal was spelled.
Where that value is zero, TimeDuration::Zero() is used instead, which is
constexpr and needs no conversion at all. - Literals fractional in their unit but whole in a finer one, respelled in
that finer unit. - Constants declared double despite holding a whole number of units and only
ever used as From* arguments. Retyping the constant moves its call sites
with it.
One of those constants was also handed back out as a float by
MainThreadIdlePeriod::GetLongIdlePeriod(), which kept its callers on the double
path, so that now returns int32_t. A caller that divides the result is
respelled /2.0 to keep the division in floating point.
Every conversion was checked to produce the same tick count as before on each
tick rate we support, so only two sites change behaviour: an atomic.wait
timeout from the WebAssembly specification and a WebRender display list build
time, both of which arrive in nanoseconds and were converted by dividing by
1000 in floating point, discarding sub-microsecond precision. FromNanoseconds
converts both exactly.
Deliberately left alone: durations that are genuinely fractional, with no exact
integer unit; the TestTimeStamp cases that exist to exercise the double
overloads; and test files, which are a separate change.
| Assignee | ||
Comment 4•1 month ago
|
||
Three sites took a TimeDuration apart into a double and rebuilt it, where the
duration arithmetic expresses the same operation directly.
TimeoutManager::RunTimeout took a quarter of a budget via ToMilliseconds().
operator/(double) is deleted on BaseTimeDuration, so operator/(int64_t) is the
intended spelling and it divides the tick count exactly. The divisor has to be
written int64_t(4): a deleted overload still takes part in overload
resolution, and int-to-int64_t and int-to-double are both Conversion rank, so
a bare 4 is ambiguous.
MediaTimer<TimeStamp>::ArmTimer already held a TimeDuration and passed it
through FromMicroseconds(ToMicroseconds()), which truncated the delay to whole
microseconds, so handing it over unchanged is also more precise. The
AwakeTimeStamp instantiation still needs a real conversion, as
AwakeTimeDuration only exposes its length as a double.
CCGCScheduler::ComputeMinimumBudgetForRunner scaled a budget by a double
multiplier through ToMilliseconds() and floored it at a millisecond.
MultDouble() and TimeDuration::Max() express that directly.
Updated•27 days ago
|
Updated•27 days ago
|
Comment 6•8 days ago
|
||
| bugherder | ||
https://hg.mozilla.org/mozilla-central/rev/d798e485d07a
https://hg.mozilla.org/mozilla-central/rev/fa04c3e26f00
https://hg.mozilla.org/mozilla-central/rev/0c9eab908b36
Comment 7•4 days ago
|
||
Perfherder has detected a build_metrics performance change from push 0c9eab908b36674b090b1d5aa3424696449eacf8.
No action is required from the author; this comment is provided for informational purposes only.
| Improvements | Test | Platform | Options | Absolute values [old vs new] |
|---|---|---|---|---|
| 4% | compiler_metrics num_static_constructors | android-5-0-armv7-nightlyasrelease | nightly-as-release | 75.00 -> 72.00 |
| 4% | compiler_metrics num_static_constructors | android-5-0-x86_64-nightlyasrelease | nightly-as-release | 75.00 -> 72.00 |
| 4% | compiler_metrics num_static_constructors | android-5-0-aarch64-nightlyasrelease | nightly-as-release | 76.00 -> 73.00 |
| 4% | compiler_metrics num_static_constructors | android-5-0-armv7-shippable | 77.00 -> 74.00 | |
| 4% | compiler_metrics num_static_constructors | android-5-0-armv7-shippable | lite | 77.00 -> 74.00 |
| ... | ... | ... | ... | ... |
| 4% | compiler_metrics num_static_constructors | fenix-android-all | 84.00 -> 81.00 |
Need Help or Information?
If you have any questions, please reach out to acseh@mozilla.com. Alternatively, you can find help on Slack by joining #perf-help, and on Matrix you can find help by joining #perftest.
Details of the alert can be found in the alert summary, including links to graphs and comparisons for each of the affected tests.
Description
•