我在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;
}
答案 0 :(得分:2)
我认为你有一种误解,QueryPerformanceFrequency
告诉你一些关于处理器速度的事情 - 事实并非如此。 QueryPerformanceFrequency
检索高分辨率性能计数器的频率,不保证与CPU时钟速度有任何可预测的关系。该值需要与QueryPerformanceCounter
结合使用才能获得高质量的计时值,而不是直接查询RDTSC的程序集。
答案 1 :(得分:1)
以下是如何使用高频定时器计时代码块的示例:
#include <Windows.h>
#include <iostream>
using namespace std;
int main()
{
LARGE_INTEGER li = {};
__int64 freq, start, stop;
QueryPerformanceFrequency(&li);
freq = li.QuadPart;
cout << "Counter Frequency: " << freq << "\n";
QueryPerformanceCounter(&li);
start = li.QuadPart;
for( int i = 0; i < 1000000; ++i )
{
int n = i * rand();
}
QueryPerformanceCounter(&li);
stop = li.QuadPart;
double elapsed_seconds = static_cast<double>(stop-start) / static_cast<double>(freq);
cout << "Elapsed Time: " << elapsed_seconds << " seconds\n";
}