Accurate timing in C/C ++

Source: Internet
Author: User

Timing A program is too important for programmers. The clock () on windows is not accurate enough, and the precision is only 10 ms, which is really sad. I have studied how to use C, C ++ timing functions in windows.
It mainly refers to the use of two functions. I first paste a piece of code that can be run and then talk about these two functions.
[Cpp]
1. # include <windows. h>
2. # include <stdio. h>
3. int main (int argc, char ** argv)
4 .{
5. LARGE_INTEGER freq;
6. LARGE_INTEGER start_t, stop_t;
7. double exe_time;
8. QueryPerformanceFrequency (& freq );
9. fprintf (stdout, "The frequency of your pc is % d. \ n", freq. QuadPart );
10. QueryPerformanceCounter (& start_t );
11. Sleep (1, 1000 );
12. QueryPerformanceCounter (& stop_t); www.2cto.com
13. exe_time = 1e3 * (stop_t.QuadPart-start_t.QuadPart)/freq. QuadPart;
14. fprintf (stdout, "Your program executed time is % fms. \ n", exe_time );
15. getchar ();
16. return 0;
17 .}

1. LARGE_INTEGER is actually a union in Microsoft's compiler. Its definition is as follows:
 
[Cpp]
1. typedef union _ LARGE_INTEGER
2 .{
3. struct
4 .{
5. DWORD LowPart;
6. LONG HighPart;
7 .};
8. struct
9 .{
10. DWORD LowPart;
11. LONG HighPart;
12.} u;
13. LONGLONG QuadPart;
14.} LARGE_INTEGER, * PLARGE_INTEGER;
If your compiler supports 64-bit integers, you can use QuadPart to reference the value of a variable. If your compiler does not support 64-bit integers, you can use LowPart and HighPart to reference the 64-bit integer's low 32-bit and high 32-bit.
2. QueryPerformanceFrequncy (LARGE_INTEGER * freq)
It is used to obtain how many times your machine executes in one second, that is, your clock cycle.
3. QueryPerformanceCounter (LARGE_INTEGER * lpPerformanceCount)
It obtains the number of clock cycles executed by the CPU since it is started.

Author: bendanban

Related Article

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.