// CpuCurve.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <assert.h>
#include <iostream>
#include <Windows.h>
#include <math.h>
using namespace std;
#define M_PI 3.1415
#define THREADCNT 4
double RunTime = 0.0; //總計的執行時間:分為sleep和do - something
DWORD WINAPI threadFunc(LPVOID param);
void Work(float c);
void CoreFunc();
int _tmain(int argc, _TCHAR* argv[])
{
DWORD coreCnt = 0;
HANDLE *hThread;
double timeCnt(0.0);
LARGE_INTEGER lFreqStart,lFreqEnd,lFreqCnt;
double Temp(0.0);
//獲得最大執行時間長度:不精確
while (abs(timeCnt < M_PI) )
{
::QueryPerformanceCounter( &lFreqStart );
Work( ( 1 + sin(timeCnt) ) );
::QueryPerformanceCounter(&lFreqEnd);
::QueryPerformanceFrequency( &lFreqCnt );
RunTime = max(RunTime,((double)(lFreqEnd.QuadPart - lFreqStart.QuadPart))/(double)(lFreqCnt.QuadPart));
timeCnt += 0.1;
}
RunTime += 0.1; //誤差校準:防止溢出
SYSTEM_INFO sysinfo;
::GetSystemInfo(&sysinfo);
coreCnt = sysinfo.dwNumberOfProcessors;
hThread = new HANDLE[coreCnt];
memset(hThread,NULL,sizeof(HANDLE)*coreCnt);
while( coreCnt-- )
{
hThread[coreCnt] = CreateThread(NULL,0,threadFunc,NULL,0,NULL);
}
DWORD dR = WaitForMultipleObjects(THREADCNT,hThread,FALSE,INFINITE);
switch (dR)
{
case WAIT_OBJECT_0:
cout<<"Thread 0 return"<<endl;
break;
case WAIT_OBJECT_0 + 1:
cout<<"Thread 1 return"<<endl;
break;
case WAIT_OBJECT_0 + 2:
cout<<"Thread 2 return"<<endl;
break;
case WAIT_OBJECT_0 + 3:
cout<<"Thread 3 return"<<endl;
break;
}
return 0;
}
DWORD WINAPI threadFunc(LPVOID param)
{
CoreFunc();
return 1;
}
void CoreFunc()
{
double timeCnt = 0.0; //時間軸線
LARGE_INTEGER lTemp = {0};
double sT,eT,fC,exeTime; //開始,結束,計數器,佔用CPU時間
QueryPerformanceFrequency(&lTemp);
fC = double(lTemp.QuadPart);
DWORD sleepTime(0);
while( 1 )
{
//do-something
QueryPerformanceCounter(&lTemp); //計時開始
sT = double(lTemp.QuadPart);
Work( sin(timeCnt) + 1);
QueryPerformanceCounter(&lTemp); //計時結束
eT = double(lTemp.QuadPart);
exeTime = (eT - sT)/fC; //獲得實際佔用CPU時間
cout<<"exeTime="<<exeTime*1000<<endl;
if( abs(RunTime - exeTime) < 0.01)
sleepTime = 0;
else
sleepTime = (DWORD)((RunTime - exeTime)*1000);
cout<<"sleepTime="<<sleepTime<<endl;
Sleep( sleepTime );
timeCnt += 0.5;
}
}
void Work(float c)
{
int ic = (int)(c*10000*20);
while( ic-- > 0)
{
for (int j = 1; j < 1000; j++ );
}
}