Why does performance.now differ so much from console.time?

783 Views Asked by At

I've just made a quick sort algorithm in javascript and now want to time it. My first approach was with console.time and console.timeEnd but after reading around a little I found out that performance.now is the better option. Only thing is that they're giving me wildly different results as you can see below:

script.js:89 performance.now: 5.099999904632568 ms
script.js:93 console.time: 1.091796875 ms

Now some of the results are better than others but most of the time there are differences of up to 5 ms. Is this just my computer behaving differently each time or am I using the methods wrong?

Here's the code:

let startTime = performance.now();
quickSort(randomArray);
let endTime = performance.now();
console.log(`performance.now: ${endTime - startTime} ms`);

console.time("console.time");
quickSort(randomArray);
console.timeEnd("console.time");

The sorting algorithm if needed:

function quickSort(array) {
    quickSortSplit(array, 0, array.length - 1);
    return array;
}

function quickSortSplit(array, low, high) {
    if (low < high) {
        let finalIndex = partition(array, low, high);

        quickSortSplit(array, low, finalIndex - 1);
        quickSortSplit(array, finalIndex + 1, high);
    }
}

function partition(array, low, high) {
    let pivotIndex = medianOfThree(array, low, high);
    let pivot = array[pivotIndex];
    array.swap(pivotIndex, high);

    let i = low - 1;
    for (let j = low; j < high; j++) {
        if (array[j] <= pivot) {
            i++;
            array.swap(j, i);
        }
    }
    array.swap(i + 1, high);
    return i + 1;
}
0

There are 0 best solutions below