精密时间测量 我用C++中的时间H来测量函数的时间。
精密时间测量 我用C++中的时间H来测量函数的时间。,c++,visual-studio-2010,chrono,ctime,C++,Visual Studio 2010,Chrono,Ctime,clock_t t = clock(); someFunction(); printf("\nTime taken: %.4fs\n", (float)(clock() - t)/CLOCKS_PER_SEC); 但是,我总是将时间取为0.0000。单独打印时,时钟()和t的值相同。我想知道是否有办法精确地测量C++中的时间(也许是纳秒量级)。我正在使用VS2010。我通常使用该函数 例如: LARGE_INTEGER frequency; // ticks per second
clock_t t = clock();
someFunction();
printf("\nTime taken: %.4fs\n", (float)(clock() - t)/CLOCKS_PER_SEC);
但是,我总是将时间取为0.0000。单独打印时,时钟()和t的值相同。我想知道是否有办法精确地测量C++中的时间(也许是纳秒量级)。我正在使用VS2010。我通常使用该函数
例如:
LARGE_INTEGER frequency; // ticks per second
LARGE_INTEGER t1, t2; // ticks
double elapsedTime;
// get ticks per second
QueryPerformanceFrequency(&frequency);
// start timer
QueryPerformanceCounter(&t1);
// do something
...
// stop timer
QueryPerformanceCounter(&t2);
// compute and print the elapsed time in millisec
elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
<>在C或C++中我通常喜欢下面。如果仍然失败,您可以考虑使用RTDSC函数
struct timeval time;
gettimeofday(&time, NULL); // Start Time
long totalTime = (time.tv_sec * 1000) + (time.tv_usec / 1000);
//........ call your functions here
gettimeofday(&time, NULL); //END-TIME
totalTime = (((time.tv_sec * 1000) + (time.tv_usec / 1000)) - totalTime);
下面的文本,我完全同意,引用(对任何C++程序员的好阅读)-< 时间测量可能需要非常高的分辨率,如果 间隔很短。在Windows中,您可以使用
GetTickCount
或
QueryPerformanceCounter
用于毫秒分辨率的函数。非常
使用中的时间戳计数器可以获得更高的分辨率
CPU,以CPU时钟频率计数
存在一个问题,“时钟频率可能会动态变化
由于中断和任务切换,测量不稳定。”C++11引入了,您可以使用获得纳秒:
auto begin = std::chrono::high_resolution_clock::now();
// code to benchmark
auto end = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count() << "ns" << std::endl;
auto begin=std::chrono::high_resolution_clock::now();
//代码到基准
自动结束=标准::时钟::高分辨率时钟::现在();
当您仅针对Windows时,QueryPerformanceFrequency
仍然是更好的选择。实际上,VS11和VS12下的高分辨率时钟
只是系统时钟
上提供中等分辨率的一种类型定义。只有在VS14中,最近才修复了此问题。x+=y-x没有意义,它相当于x=y,在您的情况下,它将丢弃旧值是的,它应该是totalTime=(…)-totalTime
计算第一次和第二次调用gettimeofday之间的差异。错误的是+=
。您可能遇到了问题。
auto begin = std::chrono::high_resolution_clock::now();
uint32_t iterations = 10000;
for(uint32_t i = 0; i < iterations; ++i)
{
// code to benchmark
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count();
std::cout << duration << "ns total, average : " << duration / iterations << "ns." << std::endl;