Another way to calculate the CPU speed.

    This site uses cookies. By continuing to browse this site, you are agreeing to our Cookie Policy.

    • Another way to calculate the CPU speed.

      Hi all,

      Here's an alternative way to calculate the CPU frequency.

      Source Code

      1. unsigned __int64 Cpu::calcCpuSpeed() const
      2. {
      3. // Calculates the CPU frequency in Hz.
      4. // Based on CPU code originally written by Emil Persson (aka Humus).
      5. LARGE_INTEGER time1, time2, freq;
      6. unsigned __int32 timeLow, timeHigh;
      7. unsigned __int64 a, b;
      8. QueryPerformanceFrequency(&freq);
      9. QueryPerformanceCounter(&time1);
      10. __asm
      11. {
      12. rdtsc ; read the time stamp counter
      13. mov timeHigh, edx ; store the upper 32-bits of counter
      14. mov timeLow, eax ; store the lower 32-bits of counter
      15. }
      16. a = unsigned __int64(timeHigh << 32) | timeLow;
      17. for (volatile int i = 0; i < 1000000; ++i)
      18. ; // spin-wait...do nothing
      19. QueryPerformanceCounter(&time2);
      20. __asm
      21. {
      22. rdtsc ; read the time stamp counter
      23. mov timeHigh, edx ; store the upper 32-bits of counter
      24. mov timeLow, eax ; store the lower 32-bits of counter
      25. }
      26. b = unsigned __int64(timeHigh << 32) | timeLow;
      27. return (b - a) * (freq.QuadPart / (time2.QuadPart - time1.QuadPart));
      28. }
      Display All


      The returned frequency is in Hz. To convert to MHz divide the result by 1000000. To convert to GHz divide by 1000000000.

      You'll need at least VC6 to compile this as VC5 doesn't support the RDTSC instruction.

      Regards,
      David Poon.

      The post was edited 1 time, last by dpoon ().