c++ - 为什么我得到不同的时间值

标签 c++ windows-7-x64 cpu-time

我在Win7x64平台上用MSVC++尝试了C++代码,我得到的CPU频率约为每秒2900000次。

当我运行这个程序时,我的秒表返回大约 10,000,000 个刻度,这意味着处理我的程序大约需要 4 秒,但我的程序结果在 1 秒(或更短)内就准备好了 O_o。

你能告诉我我的代码有什么问题吗?

#include <iostream>
#include "header.h"
#include <fstream>
#include <string>
#include <sstream>
#include <strsafe.h>
#include <direct.h>
#include <string.h>



using namespace std;

#define CV_TO_NANO 1000000000
#define CV_TO_MICRO 1000000
#define CV_TO_MILLI 1000

 unsigned __int64 inline GetRDTSC()
{
   __asm
   {
      ; Flush the pipeline
      XOR eax, eax
      CPUID
      ; Get RDTSC counter in edx:eax
      RDTSC
   }
}

unsigned __int64 RunTest(TCHAR *AppName, TCHAR *CmdLine);

 void main()
 {  
     unsigned __int64 start = 0;
     unsigned __int64 stop = 0;
     unsigned __int64 freq = 0;
     float rps;
     ofstream dataFile;


     // get processor freq
     QueryPerformanceFrequency((LARGE_INTEGER *)&freq);
     cout <<"freq (count per second): "<< freq << endl;
     // round per second
     rps = 1.0/(freq);
     cout <<"rps (1/rps): "<< rps << endl;
     dataFile.open ("d:/dataC.txt",ios::out );
     for(int i = 0;i<200;i++)
     {
        SetProcessAffinityMask(GetCurrentProcess(),0x0001);
        SetThreadAffinityMask(GetCurrentThread(),0x0001);
        cout << RunTest(L"D:\\Child\\Child.exe", NULL);
     }
    getchar();
    return;
 }

unsigned __int64 RunTest(TCHAR *AppName, TCHAR *CmdLine)
{
    unsigned __int64 start = 0;
    unsigned __int64 stop = 0;
    PROCESS_INFORMATION processInformation;
    STARTUPINFO startupInfo;
    memset(&processInformation, 0, sizeof(processInformation));
    memset(&startupInfo, 0, sizeof(startupInfo));
    startupInfo.cb = sizeof(startupInfo);

    BOOL result;
    start = GetRDTSC();
    result = ::CreateProcess(AppName, CmdLine, NULL, NULL, FALSE, REALTIME_PRIORITY_CLASS, NULL, NULL, &startupInfo, &processInformation);
    stop = GetRDTSC();
    getchar();
    if (result == 0)
    {
        wprintf(L"ERROR: CreateProcess failed!");
    }
    else
    {
        WaitForSingleObject( processInformation.hProcess, 0 );
        CloseHandle( processInformation.hProcess );
        CloseHandle( processInformation.hThread );
    }
    return stop - start;
}

最佳答案

我认为您在这里有一个误解,认为QueryPerformanceFrequency 告诉您有关处理器速度的信息 - 事实并非如此。 QueryPerformanceFrequency检索高分辨率性能计数器的频率,不保证该频率与 CPU 时钟速度有任何可预测的关系。该值需要与 QueryPerformanceCounter 配合使用为了获得高质量的计时值,而不是使用直接查询 RDTSC 的程序集。

关于c++ - 为什么我得到不同的时间值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8229067/

相关文章:

java - Android SDK安装找不到JDK

c++ - 生成三 channel LUT 掩码的有效方法

c++ - 可取消引用的迭代器

c++ - C++ 项目中的 .pro 扩展名

linux - cpu时间在虚拟机中跳跃很多

java - VisualVM 分析器 : How to test CPU Time for a method with varying parameter sizes?

使用 clock() 函数计算 C 中 system() 命令的运行时间

c++ - 奇怪的 g++ 编译器在模板函数中对 typeid 的行为

Windows 7 64Bit 上的 .NET COM Interop 让我头疼

windows - Windows 7中的声音和手势移动口吃