[clang] [llvm] [TimeProfiler] Fix duration rounding bias (PR #228677)
Arthur Eubanks via cfe-commits
cfe-commits at lists.llvm.org
Wed Nov 4 13:48:53 PST 2026
================
@@ -222,15 +232,61 @@ struct llvm::TimeTraceProfiler {
[](const auto &TTP) { return TTP->Stack.empty(); }) &&
"All profiler sections should be ended when calling write");
+ // Compute floor-rounded microsecond timestamps and clamp child start times
+ // top-down. An event's emitted end is floor(start) + floor(dur), which is
+ // floor(end) - 1 when the fractional parts of start and dur sum to >= 1us,
+ // so a parent can lose 1us while a child near its end does not. E.g.:
+ // Parent [0.5, 3.4] -> ts = 0, dur = 2 -> [0, 2]
+ // Child1 [1.0, 2.0] -> ts = 1, dur = 1 -> [1, 2]
+ // Child2 [2.0, 3.0] -> ts = 2, dur = 1 -> [2, 3] (overruns Parent)
+ // Clamping Child2 left to [1, 2] would then overlap Child1, so we walk
+ // non-overlapping siblings right-to-left to shift earlier siblings left
+ // as needed; sum(floor(d_i)) <= floor(d_parent) guarantees they fit.
+ auto clampEntries = [](TimeTraceProfiler &TTP) {
+ auto &Entries = TTP.Entries;
+ for (TimeTraceProfilerEntry &E : Entries) {
+ E.StartUs = E.getFlameGraphStartUs(TTP.StartTime);
+ E.DurUs = E.getFlameGraphDurUs();
+ }
+ for (size_t Idx = Entries.size(); Idx-- > 0;) {
+ const auto &E = Entries[Idx];
+ if (E.EventType == TimeTraceEventType::InstantEvent)
+ continue;
+ ClockType::rep PStart = E.StartUs;
+ ClockType::rep PEnd = PStart + E.DurUs;
+ ClockType::rep MaxEnd = PEnd;
+ for (uint32_t I = 0; I < E.InstantEventCount; ++I) {
+ auto &IE = Entries[Idx + 1 + I];
+ IE.StartUs = std::clamp(IE.StartUs, PStart, PEnd);
----------------
aeubanks wrote:
this could cause incorrect ordering of instant events relative to other child events right? like in your example, if we had an instant event at time 2, it originally was between child1 and child2, but now after child2 gets shifted earlier, the instant event would be after child2
https://github.com/llvm/llvm-project/pull/228677
More information about the cfe-commits
mailing list