C + + uses Windows functions to implement timing sample _c language

Source: Internet
Author: User

Copy Code code as follows:

Windows system can use time (), clock (), timeGetTime (), GetTickCount (), QueryPerformanceCounter () to time a piece of program code

#include <stdio.h>
#include <windows.h>
#include <time.h>//time_t time () clock_t clock ()
#include <Mmsystem.h>//timegettime ()
#pragma comment (lib, "Winmm.lib")//timegettime ()

How to: Replace the sleep () function with a function that requires a test run time.

int main ()
{//Time with time (), in seconds
time_t Timebegin, Timeend;
Timebegin = time (NULL);
Sleep (1000);
Timeend = time (NULL);
printf ("%d\n", Timeend-timebegin);


Use clock () to timing, in milliseconds
clock_t Clockbegin, Clockend;
Clockbegin = Clock ();
Sleep (800);
Clockend = Clock ();
printf ("%d\n", Clockend-clockbegin);


Use timeGetTime () to timing, in milliseconds
DWORD Dwbegin, Dwend;
Dwbegin = timeGetTime ();
Sleep (800);
Dwend = timeGetTime ();
printf ("%d\n", Dwend-dwbegin);


   //Timing with GetTickCount (), in milliseconds
    dword  dwgtcbegin, dwgtcend;
    Dwgtcbegin = GetTickCount ();
    Sleep (800);
    dwgtcend = GetTickCount ();
    printf ("%d\n", dwgtcend-dwgtcbegin);


Use QueryPerformanceCounter () to timing, in microseconds
Large_integer Large_interger;
Double DFF;
__int64 C1, C2;
QueryPerformanceFrequency (&large_interger);
DFF = Large_interger. QuadPart;
QueryPerformanceCounter (&large_interger);
C1 = Large_interger. QuadPart;
Sleep (800);
QueryPerformanceCounter (&large_interger);
C2 = Large_interger. QuadPart;
printf ("Native high-precision timer frequency%lf\n", DFF);
printf ("First timer value%i64d\n second timer value%i64d\n timer difference%i64d\n", C1, c2, C2-C1);
printf ("Timed%lf milliseconds \ n \ \" (C2-C1) * 1000/DFF);
return 0;
}



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.