Skip to content

Commit 291ddbc

Browse files
authored
Switch the trace viewer to binary search when attaching CPU samples. (#143)
1 parent 6b0c5af commit 291ddbc

1 file changed

Lines changed: 18 additions & 12 deletions

File tree

dial9-tokio-telemetry/trace_viewer/index.html

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -850,24 +850,30 @@ <h3>⌨ Keyboard</h3>
850850
console.log(`Found ${queueSamples.length} global queue samples`);
851851

852852
// Attach CPU samples to poll spans they fall within
853+
// Use binary search: polls are sorted by start time per worker
853854
if (trace.cpuSamples.length > 0) {
854855
for (const sample of trace.cpuSamples) {
855856
const spans = workerSpans[sample.workerId];
856857
if (!spans) { sample.spawnLoc = null; continue; }
857858
if (sample.source !== 1) spans.cpuSampleTimes.push(sample.timestamp);
858-
let found = false;
859-
for (const poll of spans.polls) {
860-
if (sample.timestamp >= poll.start && sample.timestamp <= poll.end) {
861-
if (sample.source === 1) {
862-
// SchedEvent — kernel descheduled this worker during a poll (blocking!)
863-
(poll.schedSamples ??= []).push(sample);
864-
} else {
865-
(poll.cpuSamples ??= []).push(sample);
866-
}
867-
sample.spawnLoc = poll.spawnLoc;
868-
found = true;
869-
break;
859+
const polls = spans.polls;
860+
const ts = sample.timestamp;
861+
// Binary search for rightmost poll with start <= ts
862+
let lo = 0, hi = polls.length - 1, found = false;
863+
while (lo <= hi) {
864+
const mid = (lo + hi) >> 1;
865+
if (polls[mid].start <= ts) { lo = mid + 1; } else { hi = mid - 1; }
866+
}
867+
// hi is now the index of the last poll with start <= ts
868+
if (hi >= 0 && ts <= polls[hi].end) {
869+
const poll = polls[hi];
870+
if (sample.source === 1) {
871+
(poll.schedSamples ??= []).push(sample);
872+
} else {
873+
(poll.cpuSamples ??= []).push(sample);
870874
}
875+
sample.spawnLoc = poll.spawnLoc;
876+
found = true;
871877
}
872878
if (!found) sample.spawnLoc = null;
873879
}

0 commit comments

Comments
 (0)