Obtain the CPU speed, more accurate

Source: Internet
Author: User
I used to publish an article "roughly estimate the CPU speed" to get the CPU speed, but it is not very accurate. This time I released a relatively accurate program. The principle is exactly the same, but sleep is replaced by a high-precision counter.

# 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 ());
}

Original Author: nowcan
Origin: http://nowcan.yeah.net

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.