how to measure function performance in javascript
Performance API
- Performance Timeline API
- Navigation Timing API
- User Timing API
- Resource Timing API.
https://developer.mozilla.org/en-US/docs/Web/API/Performance
performance.measure
performance.measure(name);
performance.measure(name, startMark);
performance.measure(name, startMark, endMark);
performance.measure(name, undefined, endMark);
performance.mark
performance.mark(name);
performance.now
const t1 = performance.now();
// do somethings
const t2 = performance.now();
High Resolution Time Level 2
W3C Recommendation 21 November 2019
https://www.w3.org/TR/hr-time/
const log = console.log;
const noForArrayAutoGenerator = (len = 100) => {
return [...``.padStart(len, ` `)].map((item, i) => i + 1).map((item, i) => i % 2 === 0 ? item : item + ``);
}
const arr = noForArrayAutoGenerator(1000 * 100);
function test(arr = []) {
const begin = performance.now();
for (let i = 0; i < arr.length; i++) {
// log(`item${i}`, arr[i]);
}
const end = performance.now();
const result = end - begin;
log(`result`, result)
}
test();
console.time & console.timeEnd
无返回值⚠️
const log = console.log;
console.time(`label`);
setTimeout(() => log(`zero`), 1000);
// 62
console.timeEnd(`label`);
// label: 16111.451171875 ms
https://developer.mozilla.org/en-US/docs/Web/API/Console/timeEnd
https://developer.mozilla.org/en-US/docs/Web/API/Console/time
console.log & new Date().getTime()
// new Date().getTime()
demos
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-07-20
* @modified
*
* @description performance
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link
* @solutions
*
*/
const log = console.log;
const noForArrayAutoGenerator = (len = 100) => {
return [...``.padStart(len, ` `)].map((item, i) => i + 1).map((item, i) => i % 2 === 0 ? item : item + ``);
}
// const arr = noForArrayAutoGenerator(1);
// const arr = noForArrayAutoGenerator(100);
const arr = noForArrayAutoGenerator(10000);
// const arr = noForArrayAutoGenerator(10000 * 10);
// const arr = noForArrayAutoGenerator(10000 * 1000);
function test(arr = []) {
// ReferenceError: performance is not defined
const begin = performance.now();
for (let i = 0; i < arr.length; i++) {
// log(`item${i}`, arr[i]);
}
const end = performance.now();
const result = end - begin;
log(`result`, result)
}
test();
refs
https://developer.mozilla.org/en-US/docs/Web/API/Performance
https://developer.mozilla.org/en-US/docs/Web/API/Performance/measure
https://developer.mozilla.org/en-US/docs/Web/API/Performance/mark
https://www.sitepoint.com/measuring-javascript-functions-performance/
https://levelup.gitconnected.com/different-ways-to-measure-performance-in-javascript-94785075ab96
https://stackoverflow.com/questions/313893/how-to-measure-time-taken-by-a-function-to-execute
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!