A little achievement of accurate timing in C #

Source: Internet
Author: User
Tags emit

All of the followingCodeRunning Environment: Windows 2003, Intel (r) core (TM) 2 Duo CPU e8400 @ 3.00 GHz 2.99 GHz, GB memory

According to someArticle, Precise timing mainly includes the following methods

1. Call gettickcount in win api
 
  [Dllimport ("Kernel32")]
Static Extern UintGettickcount ();

The number of milliseconds that have elapsed since the operating system was started. The precision is 1 ms. After a simple test, it is found that the error is about 15 ms.

Disadvantage: the return value is uint, and the maximum value is the power of 32. Therefore, if the server is continuously started for about 49 days, the return value obtained by this method will be zero.

Usage:

 
Uint S1 = gettickcount (); thread. Sleep (2719); console. writeline (gettickcount ()-S1); // unit: milliseconds
2. Call timegettime in win api Recommendation
 
  [Dllimport ("Winmm")]
Static Extern UintTimegettime ();

It is often used in multimedia timers. Similar to gettickcount, it is also the number of milliseconds that have elapsed since the operating system was started. The precision is 1 ms.

Generally, the default precision is more than 1 Millisecond (different operating systems). You need to call timebeginperiod and timeendperiod to set the precision.

  [Dllimport (  "  Winmm  "  )]
Static Extern Void Timebeginperiod ( Int T );
[Dllimport ( " Winmm " )]
Static Extern Void Timeendperiod ( Int T );

Disadvantage: Like gettickcount, it is limited by the maximum number of digits returned.

Usage:

 
Timebeginperiod (1); uint start = timegettime (); thread. Sleep (2719); console. writeline (timegettime ()-Start); // The unit is millisecond timeendperiod (1 );
3. Call the built-in. Net method system. environment. tickcount

Obtain the number of milliseconds after the system is started. After decompilation, it may also be called gettickcount, but its return value is int. In the prototype of the gettickcount and timegettime methods, the return value is DWORD, which corresponds to the uint in C. net to system. environment. what else does tickcount do?
Disadvantage: Like gettickcount, it is limited by the maximum number of digits returned.

Usage:

 
Int AA = system. environment. tickcount; thread. Sleep (2719); console. writeline (system. environment. tickcount-aa); // unit: milliseconds

 

 Note: After testing, it is found that gettickcount, system. environment. tickcount can also be set with timebeginperiod and timeendperiod. The maximum precision can be increased to 1 ms. Why?

4. Call queryperformancecounter in win api
  [Dllimport ("Kernel32.dll")]
Static Extern BoolQueryperformancecounter (RefLongLpperformancecount );

Used to obtain the value of a high-precision timer (if such a timer exists. Microsoft interprets this API as a counter growth value per second.
If the installed hardware does not support high-precision timers, the function returns false and needs to work with another API function queryperformancefrequency.

  [Dllimport ("Kernel32")]
Static Extern BoolQueryperformancefrequency (Ref LongPerformancefrequency );

Queryperformancefrequency returns the frequency of high-precision counters supported by hardware. If the installed hardware does not support high-precision timers, the function returns false.

Usage:

Long a = 0; queryperformancefrequency (Ref A); long B = 0, c = 0; queryperformancecounter (ref B); thread. sleep (2719); queryperformancecounter (ref C); console. writeline (c-B)/(decimal) A); // unit: seconds

The precision is one second per million. In addition, because it is of the long type, there is no insufficient number of the preceding APIs.

Disadvantages: in an article, we can see that the API results are slow in the energy-saving mode and fast in the super-frequency mode. In addition, the effect is different when the battery is used and when the power supply is used (notebook)
Original address: http://delphi.xcjc.net/viewthread.php? Tid = 1570
If it is true, the results of the API may not be accurate.

5. Use the. NET system. Diagnostics. Stopwatch class Recommendation

In the Basic timer mechanism, stopwatch counts the timer scale to measure the running time. If the installed hardware and operating system support high-resolution performance counters, the stopwatch class uses this counter to measure the running time; otherwise, the stopwatch class uses the system counter to measure the running time. Use the frequency and ishighresolution static fields to determine the precision and resolution of stopwatch timing.

In fact, it encapsulates two win APIs: queryperformancecounter and queryperformancefrequency. If the hardware supports high precision, queryperformancecounter is called. If not, datetime. ticks is used for calculation.

Usage:

Stopwatch Sw = new stopwatch (); Sw. start (); thread. sleep (2719); Sw. stop (); console. writeline (SW. elapsedticks/(decimal) stopwatch. frequency );
6. Use the CPU timestamp for more precise timing

Address: http://www.chinaunix.net/jh/23/110190.html

I am not very familiar with the principle of this method, and the hardware knowledge is too scarce. Precision is NS

To use this method in C #, you must first create a managed C ++ Project (because the compilation is embedded) and compile it into a DLL for C # to call.

C ++ code:

// Mltimerdot. h # pragma onceusing namespace system; namespace mltimerdot {// get the clock cycle from the computer startup to the present unsigned _ int64 getcyclecount (void) {_ ASM _ emit 0x0f _ ASM _ emit 0x31} // statement. net class public _ GC class mltimer {public: mltimer (void) {}// calculate the clock cycle uint64 getcount (void) {return getcyclecount ();}};}

C # call:

 
Long a = 0; queryperformancefrequency (Ref A); mltimerdot. mltimer timer = new mltimerdot. mltimer (); ulong Ss = timer. getcount (); thread. sleep (1, 2719); console. writeline (timer. getcount ()-SS)/(decimal) );

Disadvantage: Like queryperformancecounter, the results are not stable.

 

My conclusion: In conventional applications, timegettime is enough, and the precision is adjusted to 1 millisecond. In most cases, timegettime is enough. System. Diagnostics. Stopwatch is also recommended for convenient calling.

 

 

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.