增加c++中的时间分辨率



我正在编写一段代码,它将告诉我执行"代码块"所花费的时间。对于这个问题,我的方法是创建timer_t的两个实例,在开始执行该"代码块"之前给第一个实例当前时间,然后给第二个实例当前时间,当它完成执行。然后取两个实例的差值来计算运行时间。代码看起来像这样:(Visual Studio使用)

#include "stdafx.h"
#include<stdio.h>
#include<conio.h>
#include<iostream>
#include<Windows.h>
#include<stdlib.h>
#include<time.h>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{

    srand((unsigned)time(NULL));

    for(int i=0;i<10;i++)
    {
        cout<<rand()%100<<endl;
    }

    cout<<endl;
    time_t timernow,timerthen;
    timernow=time(NULL);
    Sleep(300);
    timerthen=time(NULL);
    cout<<"Elapsed time: "<<timerthen-timernow;
    _getch();

    return 0;
}

但问题是,它给我的时间只有几秒(0在这种情况下,而不是0.3),但我想要的时间毫秒左右。有可能提高时间的分辨率/精度吗?谢谢你。

使用<chrono>。具有高精度时钟和duration_cast等时间测量设备。

最新更新