Sub-millisecond precision timing in C or C++

前端 未结 9 1062
天命终不由人
天命终不由人 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;
    

提交回复
热议问题