자바스크립트 코드 실행시간 측정하기
가장 먼저, console.time을 이용할 수 있다.
console.time과 console.timeEnd 사이의 시간 차이를 출력할 수 있다.
인자로 같은 문자열을 넣으면, 그 사이에서 실행된 코드들이 얼마만큼의 시간동안 실행되었는지 콘솔로 확인할 수 있다.
그 사이에서 console.timeLog를 사용하면 콘솔 코드가 실행된 순간에 시간이 얼마나 지났는지도 확인할 수 있다.
const checker = () => {
for(let i = 0; i <= 100000; i++) {
for(let j = 0; j <= 100000; j++) {}
}
}
console.time("check fn");
checker();
console.timeEnd("check fn");
// check fn: 3144.93896484375 ms
https://developer.mozilla.org/en-US/docs/Web/API/console/timeEnd
console.timeEnd() - Web APIs | MDN
The console.timeEnd() stops a timer that was previously started by calling console.time().
developer.mozilla.org
또 다른 방법으로 performance를 사용할 수 있다.
const start = performance.now();
checker();
const end = performance.now();
console.log(end - start); // 3146.39999999851
또는
performance.mark('start')
checker();
performance.mark('end');
const result = performance.measure('check benchmark', 'start', 'end');
console.log(result.duration); // 3153.400000002235
위의 performance.measure 코드는 PerformanceMeasure 객체를 반환한다.
이 객체 내부에 duration이 코드가 실행되는데 걸린 시간을 담는다.
https://developer.mozilla.org/ko/docs/Web/API/Performance
Performance - Web API | MDN
The Performance interface represents timing-related performance information for the given page.
developer.mozilla.org
🫘 예시로 for, for of, forEach의 성능을 측정해볼 수 있다.
const arr = new Array(10000).fill(0);
console.time("for");
for(let i = 0; i < 10000; i++) {
const a = arr[i];
}
console.timeEnd("for");
console.time("forEach");
arr.forEach(el => {
const a = el;
})
console.timeEnd("forEach");
console.time("for of");
for(let i of arr) {
const a = i;
}
console.timeEnd("for of");
위 코드의 결과값은 당연히도 매번 다르게 나오지만, 대체로 forEach > for of > for 순으로 빠른 성능을 보여주었다.
🍭 react native에서는 위의 코드 중에서 performance.now()가 유일하게 작동하였다.
JS 벤치마킹 라이브러리로 benchmark를 사용할 수도 있다.
https://www.npmjs.com/package/benchmark
benchmark
A benchmarking library that supports high-resolution timers & returns statistically significant results.. Latest version: 2.1.4, last published: 6 years ago. Start using benchmark in your project by running `npm i benchmark`. There are 231 other projects i
www.npmjs.com