Question

I am trying to calculate the delta in milliseconds with something like this:

int olddelta = 0;
    int delta = 0;
    const clock_t begin_time = clock();
    while (true) {
        olddelta=delta;
        delta=clock()-olddelta;
        cout<<delta<<endl;
}

however this is not working as the delta is definitely not over 4000, and it seems to get progressively higher. What have i done incorrectly?

Was it helpful?

Solution

Since you are using clock(), you need to divide it by CLOCKS_PER_SEC to obtain the result expressed in seconds. To get fractions, cast clock() to double before the division:

double olddelta = 0;
double delta = 0;
const double begin_time = clock();
while (true) {
    olddelta = delta;
    delta=clock()-olddelta;
    cout << (delta/CLOCKS_PER_SEC) << endl;
}

If you want to measure the time of a single iteration, change the loop as follows:

double olddelta = 0;
double delta = 0;
const double begin_time = clock();
while (true) {
    double now = clock();
    delta = now - begin_time;
    cout << (delta/CLOCKS_PER_SEC) << endl;
    begin_time = now;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top