<script>
// sort 메서드 사용하지 않고 O(N^2) 정렬 시간 비교
// bubblesort
function bubbleSort(arr) {
const n = arr.length;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n - i - 1; j++) {
if (arr[j + 1] < arr[j]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
// sort() method
function sortM(arr) {
arr.sort((a, b) => a - b);
return arr;
}
// time measure
function measureTime(callback, arr) {
const start = performance.now();
const result = callback(arr);
const end = performance.now();
return [end - start, result];
}
// 10000 ~ 1
let arr = Array.from({ length: 10000 }, (_, k) => 10000 - k);
console.log(arr);
// bubblesort time measure
const [bubbleTime, bubbleSortResult] = measureTime(bubbleSort, arr);
console.log(
`bubblesort time: ${bubbleTime} , bubbleSort result: ${bubbleSortResult}`
);
// doSortTime: 0.19999999925494194 , doSortTimeResult:
// sort() time measure
arr = Array.from({ length: 10000 }, (_, k) => 10000 - k);
const [doSortTime, doSortTimeResult] = measureTime(sortM, arr);
console.log(
`doSortTime: ${doSortTime} , doSortTimeResult: ${doSortTimeResult}`
);
// doSortTime: 0.19999999925494194 , doSortTimeResult:
// doSortTime: 0.19999999925494194 , doSortTimeResult:
</script>
시간 측정 시
performance.now()로 시작 시간 담아두기
측정할 함수 실행
실행이 끝난 후 performance.now()로 끝난 시간 담아두기
-> start - end
performance.now()로 마이크로초(µs) 단위까지 정밀한 시간 측정가능
- 정밀한 시간 측정 시에만 사용
Date.now()는 s까지 측정