简体   繁体   中英

inconsistent clock_gettime performance

I'm trying to time some C++ code, but I was getting odd results. I wrote this test program to try to isolate what was going on. Can anyone explain the results? This was run on Ubuntu 11.04 and an EC2 medium High CPU instance if that's relevant

#include <iostream>
#include <time.h>
using namespace std;

int main()
{
    timespec startTime, currentTime;
    long elapsed;

    for (int i=0; i<5; i++) {
        clock_gettime(CLOCK_REALTIME, &startTime);
        sleep(1);
        clock_gettime(CLOCK_REALTIME, &currentTime);
        elapsed = currentTime.tv_nsec - startTime.tv_nsec;
        cout << elapsed << " nanoseconds elapsed" << endl;
        cout << "1000000000 expected" << endl;
    }
    return 0;
}

Output:

109044 nanoseconds elapsed
1000000000 expected
133713 nanoseconds elapsed
1000000000 expected
197287 nanoseconds elapsed
1000000000 expected
143396 nanoseconds elapsed
1000000000 expected
111871 nanoseconds elapsed
1000000000 expected

You also have to account that the current time may have rolled over into the next second. The nanosecond field only tells you how far you have gone in time in the current second.

    elapsed = (currentTime.tv_sec - startTime.tv_sec) * 1000000000
              + currentTime.tv_nsec - startTime.tv_nsec;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM