dimanche 19 mars 2023

Why does high resolution clock from chrono library output 0 and reasonable values in seemingly random order?

I have a function that I was using the chrono library to benchmark- at times the output would be zero for time passed and sometimes a more reasonable value- in my case about 973,300 nanoseconds. I would like to know why this behaviour occurs specifically- as in why sometimes the output is zero but sometimes the 973,300 nanoseconds I mentioned above. I understand that there is a limit on precision intrinsic to any machine, but the fact that there is an output at times 0 or at other times more reasonable is what is getting to me.

#include <chrono>
#include <iostream>
using namespace std;

void megu()
{
    for(int i = 0; i < 1000000; i++);
}

int main()
{
    auto start = chrono::high_resolution_clock::now();
    megu();
    auto end = chrono::high_resolution_clock::now();
    auto duration = chrono::duration_cast<chrono::nanoseconds>(end - start);
    cout << duration.count();

    return 0;
}

I attempted to run the code with longer and shorter run time functions (larger maximum value for i in function megu here, and it only happens with shorter run times. This points to it being a precision issue- if it was not for the "reasonable" values outputted in between the zero's having a low variance- maximum of 20 nanoseconds of difference between them (within that 973,300 nanosecond window). The sudden zero's then, have to be due to something else. I also tried running the function as many times as necessary in order to get X amount of reasonable values to take a decent average, and I do get enough of these reasonable values every time within a single program execution using a loop that discards 0 values (no batch file etc).

I am on Windows 11, Intel i7 processor.

Aucun commentaire:

Enregistrer un commentaire