Performance Marks Measure Time Spans

Drop marks around work and read the spans back with measure; entries stay buffered for later inspection instead of ad hoc timing prints.

JavascriptCli Tooling

Code

javascriptsnippet
20 lines
// mark 打点,measure 计算两个打点之间的时长
performance.mark('validate:start');
let checksum = 0;
for (let i = 0; i < 500_000; i++) checksum = (checksum + i) % 997;
performance.mark('validate:end');
const validate = performance.measure('validate', 'validate:start', 'validate:end');
console.log('validate duration recorded:', validate.duration >= 0);

// 起点缺省为时间原点:整个进程到当前打点的总时长
performance.mark('now');
const total = performance.measure('total', undefined, 'now');
console.log('total >= validate:', total.duration >= validate.duration);

// 打点与测量都进入 buffer,可按类型事后枚举
console.log('marks:', performance.getEntriesByType('mark').map((e) => e.name).join(', '));
console.log('measures:', performance.getEntriesByType('measure').map((e) => e.name).join(', '));

// 同一对打点重复 measure 得到同一时长
const again = performance.measure('validate-again', 'validate:start', 'validate:end');
console.log('repeatable:', Math.abs(again.duration - validate.duration) < 0.01);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

validate duration recorded: true
total >= validate: true
marks: validate:start, validate:end, now
measures: total, validate
repeatable: true

Marks and measures

performance.mark(‘validate:start’) and validate:end bracket a 500k-iteration loop; performance.measure(‘validate’, …) computes the span and returns the entry whose duration is checked with >= 0. The marks persist in the buffer rather than being consumed.

Whole-run spans

A measure with an undefined start (performance.measure(‘total’, undefined, ‘now’)) begins at the time origin, so total >= validate prints true — the whole-run span cannot be shorter than the segment.

Replay from the buffer

getEntriesByType(‘mark’) lists the three mark names and getEntriesByType(‘measure’) lists all measures. Re-measuring the same pair (validate-again) lands within 0.01ms, printed as repeatable: true, because both reads come from the same buffered timestamps.

Interactive Tools for This Topic

FAQ

Does measuring a span consume the marks?
No. Marks stay in the performance buffer, which is why the same pair can be measured again (validate-again) with the same result.
What does an undefined start mean in measure()?
The span begins at the time origin, so the measure covers the whole run up to the end mark — the demo checks total >= validate.