How to get CPU's frequency C + +

Source: Internet
Author: User
Tags sleep function

Refer to the online code, add a little bit of their own comments, I hope you will have a harvest.

Longlong getfrequency (DWORD sleeptime)//Get CPU Frequency

{

DWORD low1 = 0, high1 = 0, Low2 = 0, high2 = 0;

Large_integer fq,st,ed;

/* The QueryPerformanceFrequency () function should be called before timing to obtain the clock frequency of the machine's internal timer. Then in

Require strictly timed events before and after the occurrence of each call QueryPerformanceCounter (), using two acquired technology

The difference and the frequency of the clock, you can calculate the time experienced accurate time. */

:: QueryPerformanceFrequency (&FQ); Precise timing (returns the frequency of high precision counters supported by the hardware)

:: QueryPerformanceCounter (&ST); Get Start time

__asm{//Get current CPU number of times

Rdtsc

mov low1, eax

mov high1, edx

}

:: Sleep (Sleeptime); Suspend thread for a moment

:: QueryPerformanceCounter (&ed); Get End time

__asm{

RDTSC//Read CPU timestamp counter

mov low2, eax

mov high2, edx

}

Converts the number of time cycles in the CPU to 64-bit integers

Longlong begin = (longlong) high1<<32 | Low1;

Longlong end = (longlong) high2<<32 | Low2;

Divides the number of CPU cycles that are obtained two times by the interval, that is, the frequency of the CPU

Because Windows ' sleep function has an error of about 15 milliseconds, the exact timing of Windows is accurate

Return (End-begin) *fq. quadpart/(ed. Quadpart-st.quadpart);

}

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.