我已經在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;
}
不能被編譯的x64。 x64不支持'asm'。 –
你應該使用'__rdtsc()'內部的windows x64 – Necrolis
謝謝你的建議。當我使用QueryPerformanceCounter()時,QueryPerformanceCounter和__rdtsc() – user1060028