如何使用QueryPerformanceCounter来测试现有代码的性能?

时间:2017-12-02 08:40:12

标签: c++ visual-studio counter query-performance

我在Visual Studio中有一个现有项目,主文件调用一个函数文件。我还按照Microsoft指南中的步骤创建了CodeTimer.cpp,并将其与必要的标题一起放在与我的代码和函数相同的目录中。

问题是,我不知道如何链接它们。解决方案构建正常,所有三个文件结合在一起,没有错误。但是当我按CTRL-F5时,我只看到了main的输出,原因显而易见(我没有将CodeTimer链接到main)。

这是我的CodeTimer:

#include "stdafx.h"
#include <tchar.h>
#include <windows.h>

using namespace System;

int _tmain(int argc, _TCHAR* argv[])
{
    __int64 ctr1 = 0, ctr2 = 0, freq = 0;
    int acc = 0, i = 0;

    // Start timing the code.
    if (QueryPerformanceCounter((LARGE_INTEGER *)&ctr1) != 0)
    {
        // Code segment is being timed.
        for (i = 0; i<100; i++) acc++;

        // Finish timing the code.
        QueryPerformanceCounter((LARGE_INTEGER *)&ctr2);

        Console::WriteLine("Start Value: {0}", ctr1.ToString());
        Console::WriteLine("End Value: {0}", ctr2.ToString());

        QueryPerformanceFrequency((LARGE_INTEGER *)&freq);

        Console::WriteLine("QueryPerformanceFrequency : {0} per Seconds.", freq.ToString());
        Console::WriteLine("QueryPerformanceCounter minimum resolution: 1/{0} Seconds.", freq.ToString());
        Console::WriteLine("ctr2 - ctr1: {0} counts.", ((ctr2 - ctr1) * 1.0 / 1.0).ToString());
        Console::WriteLine("65536 Increments by 1 computation time: {0} seconds.", ((ctr2 - ctr1) * 1.0 / freq).ToString());
    }
    else
    {
        DWORD dwError = GetLastError();
        Console::WriteLine("Error value = {0}", dwError.ToString());
    }

    // Make the console window wait.
    Console::WriteLine();
    Console::Write("Press ENTER to finish.");
    Console::Read();

    return 0;
}

1 个答案:

答案 0 :(得分:0)

NVM修复了它。只需在我的代码下的main()函数中添加_tmain()的主体,并完全获取CodeTimer.cpp文件。这是一个主电源冲突(一个项目中有多个主电源,编译器自动输出项目中具有最高优先级的电源)。