Sub-millisecond precision timing in C or C++

前端 未结 9 1048
天命终不由人
天命终不由人 2020-12-03 15:37

What techniques / methods exist for getting sub-millisecond precision timing data in C or C++, and what precision and accuracy do they provide? I\'m looking for methods tha

相关标签:
9条回答
  • 2020-12-03 16:08

    timeval in sys/time.h has a member 'tv_usec' which is microseconds.

    This link and the code below will help illustrate:

    http://www.opengroup.org/onlinepubs/000095399/basedefs/sys/time.h.html

    timeval start;
    timeval finish;
    
    long int sec_diff;
    long int mic_diff;
    
    gettimeofday(&start, 0);
    cout << "whooo hooo" << endl;
    gettimeofday(&finish, 0);
    
    sec_diff = finish.tv_sec - start.tv_sec;
    mic_diff = finish.tv_usec - start.tv_usec;
    
    cout << "cout-ing 'whooo hooo' took " << sec_diff << "seconds and " << mic_diff << " micros." << endl;
    
    gettimeofday(&start, 0);
    printf("whooo hooo\n");
    gettimeofday(&finish, 0);
    
    sec_diff = finish.tv_sec - start.tv_sec;
    mic_diff = finish.tv_usec - start.tv_usec;
    
    cout << "fprint-ing 'whooo hooo' took " << sec_diff << "seconds and " << mic_diff << " micros." << endl;
    
    0 讨论(0)
  • 2020-12-03 16:09

    The hardware (and therefore resolution) varies from machine to machine. On Windows, specifically (I'm not sure about other platforms), you can use QueryPerformanceCounter and QueryPerformanceFrequency, but be aware you should call both from the same thread and there are no strict guarantees about resolution (QueryPerformanceFrequency is allowed to return 0 meaning no high resolution timer is available). However, on most modern desktops, there should be one accurate to microseconds.

    0 讨论(0)
  • 2020-12-03 16:09

    You may try the following:

    struct timeval t; gettimeofday(&t,0x0);

    This gives you current timestamp in micro-seconds. I am not sure about the accuracy.

    0 讨论(0)
提交回复
热议问题