得到CPU的速度,較精確

來源:互聯網
上載者:User
以前發布過一篇文章《粗數量級估計CPU的速度》可以得到CPU的速度,但是不是很准,這次發布一個比較準的程式。原理完全一樣,只是用高精度計數器代替了Sleep。

#include
#include

int __fastcall Frequence_MHz()
{
LARGE_INTEGER ulFreq, ulTicks, ulValue, ulResult;
__int64 ulEAX_EDX, ulStartCounter;
DWORD PriorityClass, Priority;

PriorityClass = GetPriorityClass(GetCurrentProcess());
Priority = GetThreadPriority(GetCurrentThread());

SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);

// it is number of ticks per seconds
QueryPerformanceFrequency(&ulFreq);

// current valueofthe performance counter
QueryPerformanceCounter(&ulTicks);

// calculate one second interval
ulValue.QuadPart = ulTicks.QuadPart + ulFreq.QuadPart;

// read time stamp counter
// this asm instruction load the highorder 32 bit of the register into EDX
// and the lower order 32 bits into EAX
_asm {
rdtsc
mov DWORD PTR ulEAX_EDX, EAX
mov DWORD PTR (ulEAX_EDX + 4), EDX
}

// start no of ticks
ulStartCounter = ulEAX_EDX;

// loop for 1 second
do {
QueryPerformanceCounter(&ulTicks);
} while (ulTicks.QuadPart <= ulValue.QuadPart);

// get the actual no of ticks
_asm {
rdtsc
mov DWORD PTR ulEAX_EDX, EAX
mov DWORD PTR (ulEAX_EDX + 4), EDX
}

// calculate result
ulResult.QuadPart = ulEAX_EDX - ulStartCounter;

SetThreadPriority(GetCurrentThread(), Priority);
SetPriorityClass(GetCurrentProcess(), PriorityClass);

return (int)ulResult.QuadPart / 1000000;
}

int main()
{
printf("CPU speed = %d MHz/n",Frequence_MHz());
}

原作者:NowCan
來 源:http://nowcan.yeah.net

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.