c++ - 在 C++ 中为函数计时

标签 c++ multithreading timer mutex

我想计算一个函数在 C++ 中花费的时间(以毫秒为单位)。

这是我所拥有的:

#include<iostream>
#include<chrono>           
using timepoint = std::chrono::steady_clock::time_point;

float elapsed_time[100];

// Run function and count time
for(int k=0;k<100;k++) {

    // Start timer
    const timepoint clock_start = chrono::system_clock::now();

    // Run Function
    Recursive_Foo();

    // Stop timer
    const timepoint clock_stop = chrono::system_clock::now();

    // Calculate time in milliseconds
    chrono::duration<double,std::milli> timetaken = clock_stop - clock_start;
    elapsed_time[k] = timetaken.count();
}

for(int l=0;l<100;l++) {
    cout<<"Array: "<<l<<" Time: "<<elapsed_time[l]<<" ms"<<endl;
}

这可以编译,但我认为多线程阻止它正常工作。输出以不规则的间隔产生时间,例如:

Array: 0 Time: 0 ms
Array: 1 Time: 0 ms
Array: 2 Time: 15.6 ms
Array: 3 Time: 0 ms
Array: 4 Time: 0 ms
Array: 5 Time: 0 ms
Array: 6 Time: 15.6 ms
Array: 7 Time: 0 ms
Array: 8 Time: 0 ms

我需要使用某种互斥锁吗?或者是否有更简单的方法来计算函数执行所需的毫秒数?

编辑

也许人们建议使用 high_resolution_clocksteady_clock,但所有这三个都会产生相同的不规则结果。

这个解决方案似乎产生了真实的结果:How to use QueryPerformanceCounter?但我不清楚为什么。另外,https://gamedev.stackexchange.com/questions/26759/best-way-to-get-elapsed-time-in-miliseconds-in-windows效果很好。似乎是 Windows 实现问题。

最佳答案

Microsoft 在几微秒内提供了一个漂亮、干净的解决方案,来自:MSDN

#include <windows.h>

LONGLONG measure_activity_high_resolution_timing()
{
    LARGE_INTEGER StartingTime, EndingTime, ElapsedMicroseconds;
    LARGE_INTEGER Frequency;

    QueryPerformanceFrequency(&Frequency); 
    QueryPerformanceCounter(&StartingTime);

    // Activity to be timed

    QueryPerformanceCounter(&EndingTime);
    ElapsedMicroseconds.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart;


    //
    // We now have the elapsed number of ticks, along with the
    // number of ticks-per-second. We use these values
    // to convert to the number of elapsed microseconds.
    // To guard against loss-of-precision, we convert
    // to microseconds *before* dividing by ticks-per-second.
    //

    ElapsedMicroseconds.QuadPart *= 1000000;
    ElapsedMicroseconds.QuadPart /= Frequency.QuadPart;
    return ElapsedMicroseconds.QuadPart;
}

关于c++ - 在 C++ 中为函数计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33336049/

相关文章:

C++ 错误 : was not declared in this scope with private after public

multithreading - 如何计算阿姆达尔定律的线程有效性

c++ - 为什么我的查找阶乘的 C++ 代码不起作用?

c# - 在主线程忙时连续更新UI

c# - 如何在 Application_BeginRequest 中执行击中网络服务器的第一个请求的部分代码?

javascript - 在 JavaScript 中使用 window.setInterval 方法的基于 Web 的计时器应用程序在移动浏览器(Chrome、Firefox 等)上无法正常工作

android - 在 Android 2.2 中设置按钮布局

java - 计算处理程序中的剩余时间

c++ - g++ libc.so 绝对路径交叉编译错误

c++ - `#input`类型的宏字符串在C++中是如何分配的?