使用 user timing api 分析 javascript 运行时性能,核心做法是调用 performance.mark() 记录关键节点,用 performance.measure() 计算区间耗时,最后通过 performance.getentriesbytype('measure') 获取数据。开发者只需在代码逻辑的前后插入标记点,即可量化特定函数的执行时间或异步操作的等待时长,从而定位性能瓶颈。

如何标记和测量同步代码块的执行时间
对于同步执行的函数或代码块,直接在入口和出口处添加标记并生成度量数据是最直接的方法。通过在函数开始处调用 performance.mark('start-key'),在结束处调用 performance.mark('end-key'),随后使用 performance.measure('duration-name', 'start-key', 'end-key') 创建一条包含精确毫秒数的性能条目。这种方法能准确反映代码在单线程主线程上的实际占用时间,排除异步回调队列的干扰。

function analyzeSyncCode() {
performance.mark('sync-start');
// 模拟一段耗时的同步计算
let sum = 0;
for (let i = 0; i <h2>如何测量异步操作与宏任务之间的间隔</h2><p>当需要分析异步操作(如 Promise 解析、定时器触发)与后续代码执行之间的时间差时,同样利用标记机制。在异步任务发起前设置起始标记,在异步回调或 Promise.then 中设置结束标记,然后进行度量。这种方式可以揭示事件循环中任务调度的延迟,帮助判断异步流程是否造成了不必要的阻塞或等待。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill12835" title="JavaScript 测试模式"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20cf0281539.jpg" alt="JavaScript 测试模式" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill12835" title="JavaScript 测试模式" class="overflowclass">JavaScript 测试模式</a>
<p class="overflowclass">使用 Jest、Vitest 和 Testing Library 实施全面的测试策略,包括单元测试、集成测试和端到端测试,涵盖模拟、测试夹具和测试驱动开发。在编</p>
</div>
<a rel="nofollow" href="/xiazai/skill12835" title="JavaScript 测试模式" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p><img src="https://img.php.cn/upload/article/001/242/473/179463207022255.png?x-oss-process=image/resize,p_40" alt="JavaScript 运行时性能分析怎么使用 User Timing API"></p><pre class="brush:php;toolbar:false;">async function analyzeAsyncDelay() {
performance.mark('async-init');
await new Promise(resolve => setTimeout(resolve, 100));
performance.mark('async-done');
performance.measure('async-wait-time', 'async-init', 'async-done');
const measures = performance.getEntriesByType('measure');
console.log(measures[0].duration); // 输出等待时间(约100ms)
}
analyzeAsyncDelay();
getEntriesByType返回的数据结构包含哪些关键字段
调用 performance.getEntriesByType('measure') 返回的是一个 PerformanceMeasure 对象数组,每个对象包含 name、startTime、duration 和 entryType 等字段。其中 duration 是计算出的时间差,startTime 是起始标记的时间戳,entryType 固定为 "measure"。这些字段可以直接用于构建性能报告或可视化图表,无需额外计算。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










