gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:55:38 26 4
gpt4 key购买 nike

我已经在使用 MSVC++ 的 Win7x64 平台上用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com