Pergunta

I am attempting to save a file every second within +- 100ms (10% error). The problem I am having is that my timing measurement is saying that execution took 1150 ms, but in reality it appears to be 3 or 4 seconds.

What's going on?

If I issue the command, sleep(1), it appears to be very accurate. However, when I measure how long something took, it must be off by quite a bit.

I am using clock() to measure program execution. All of this stuff is within a while loop.

Walter

Foi útil?

Solução

Your problem is that clock() reports you CPU time used by your process and it is usually different from the "real" time used.

For example following code:

#include <time.h>
#include <iostream>
#include <unistd.h>

using namespace std;

int main()
{
        clock_t scl = clock();
        sleep(1);
        cout << "CPU clock time " << clock()-scl << endl;
}

gives

time ./a.out 
CPU clock time 0

real    0m1.005s
user    0m0.000s
sys 0m0.004s
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top