更精确的获取时间的方法

//利用win32 API  QueryPerformanceFrequency与QueryPerformanceCounter,可以更精确精确的计算,例如拿来测试,网络抓包的精确分析

#include

#include
#include
using namespace std;
int main() {
    LARGE_INTEGER lv,lv_b;

    // 获取每秒多少CPU Performance Tick
    QueryPerformanceFrequency( &lv );

    // 转换为每个Tick多少秒
    double secondsPerTick = 1.0 / lv.QuadPart;
    QueryPerformanceCounter( &lv_b );
    for ( size_t i = 0; i < 100; ++i ) {
        // 获取CPU运行到现在的Tick数
        QueryPerformanceCounter( &lv );
        cout.precision( 6 );
        // 计算CPU运行到现在的时间
        // 比GetTickCount和timeGetTime更加精确
        LONGLONG duration = lv.QuadPart-lv_b.QuadPart;
        double timeElapsedTotal = secondsPerTick * duration;
        cout << fixed << showpoint << timeElapsedTotal << endl;
        //printf( "%lf \n", timeElapsedTotal ) ;
    }
    return 0;
}

你可能感兴趣的:(更精确的获取时间的方法)