A little bit of precision timing in C #

Source: Internet
Author: User

All of the following code runs the environment: Windows 2003, Intel (R) Core (TM) 2 Duo CPU E8400 @ 3.00GHz 2.99GHZ,2.96GB Memory

According to some articles on the integrated Web, accurate timekeeping is mainly in the following ways

1 calling the GetTickCount in the win API
 
   [DllImport ("kernel32")]
static extern uint GetTickCount ();

The number of milliseconds that have elapsed since the operating system started up to now, with a precision of 1 milliseconds, has been tested to find that the error is about 15MS

Disadvantage: The return value is uint and the maximum value is 2 of 32, so if the server is powered on for approximately 49 days, the return value obtained by the method will be zeroed

Usage:

?
123 uints1 = GetTickCount();Thread.Sleep(2719);Console.WriteLine(GetTickCount() - s1); //单位毫秒
2 calling the timeGetTime recommendation in the win API
 
   [DllImport ("winmm")]
static extern uint timeGetTime ();

Commonly used in multimedia timers, similar to GetTickCount, and also returns the number of milliseconds the operating system has been booted to now, with a precision of 1 milliseconds.

The general default accuracy is more than 1 milliseconds (different operating systems differ), 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: As with GetTickCount, the maximum number of digits is limited by the return value.

Usage:

?
12345 timeBeginPeriod(1);uintstart = timeGetTime();Thread.Sleep(2719);Console.WriteLine(timeGetTime() - start); //单位毫秒timeEndPeriod(1);
3 How to call the. NET self-System.Environment.TickCount

Gets the number of milliseconds that have elapsed since the system started. Anti-compilation guesses that it may also be the gettickcount of the call, but its return value is int, and the return value in the prototype of GetTickCount and timeGetTime method is a DWORD, corresponding to the UINT in C #. NET what else do you do with System.Environment.TickCount?
Disadvantage: As with GetTickCount, the maximum number of digits is limited by the return value.

Usage:

?
123 intaa = System.Environment.TickCount;Thread.Sleep(2719);Console.WriteLine(System.Environment.TickCount - aa); //单位毫秒

Note : After testing, it is found that GetTickCount, System.Environment.TickCount can also be used timebeginperiod and timeendperiod to set the accuracy, the highest accuracy can be increased to 1 milliseconds. I don't know what the reason is.

4 calling the QueryPerformanceCounter in the win API
 
   [DllImport ("kernel32.dll")]
static extern bool QueryPerformanceCounter (ref long Lpperformancecount);

The value used to get a high-precision timer (if such a timer exists). Microsoft's explanation of this API is the value of a counter growth per second.
If the installed hardware does not support a high-precision timer, the function returns false and needs to mate with another API function, QueryPerformanceFrequency.

 
   [DllImport ("kernel32")]
static extern bool QueryPerformanceFrequency (ref long performancefrequency);

QueryPerformanceFrequency returns the frequency of hardware-supported high-precision counters, and returns False if the installed hardware does not support high-precision timers.

Usage:

?
1234567 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 //unit seconds

The accuracy is one out of 10,000 seconds. And because it is a long type, there is no problem with the above few API bits.

Cons: In an article to see, the API in the energy-saving mode when the results are slow, overclocking mode is fast, and battery and power when the effect is not the same (notebook)
Original address: http://delphi.xcjc.net/viewthread.php?tid=1570
Without overclocking and other tests, if true, the API's results may not be allowed.

5 Recommended for System.Diagnostics.Stopwatch class using. Net

The Stopwatch counts the ticks in the base timer mechanism to measure elapsed time. If the installed hardware and operating system support counters for high-resolution performance, the Stopwatch class will use this counter to measure elapsed time, otherwise the Stopwatch class will use system counters to measure elapsed time. Use Frequency and ishighresolution two static fields to determine the accuracy and resolution of the Stopwatch timing.

In fact it is the QueryPerformanceCounter, queryperformancefrequency two win API package, if the hardware support high precision, call QueryPerformanceCounter, If not supported, use Datetime.ticks to calculate.

Usage:

?
12345 Stopwatch sw = newStopwatch();sw.Start();Thread.Sleep(2719);sw.Stop();Console.WriteLine(sw.ElapsedTicks / (decimal)Stopwatch.Frequency);
6 higher precision timing with CPU timestamps

Original address: http://www.chinaunix.net/jh/23/110190.html

The principle of this method I do not quite understand that hardware knowledge is too scarce. Accuracy is NS

In C # To use this method must first build a managed C + + project (because to be inline assembly), compiled into a DLL for C # call, a bit cumbersome.

C + + code:

?
123456789101112131415161718192021222324252627282930313233 // MLTimerDot.h#pragma onceusing namespace System;namespace MLTimerDot { //得到计算机启动到现在的时钟周期 unsigned __int64 GetCycleCount(void) { _asm _emit 0x0F _asm _emit 0x31 } //声明 .NET 类 public __gc class MLTimer { public: MLTimer(void) { } //计算时钟周期 UInt64 GetCount(void) { return GetCycleCount(); } }; }

C # calls:

?
1234567 longa = 0;QueryPerformanceFrequency(ref a); MLTimerDot.MLTimer timer = newMLTimerDot.MLTimer();ulong ss= timer.GetCount();Thread.Sleep(2719);Console.WriteLine((timer.GetCount() - ss) / (decimal)a);

Cons: As with QueryPerformanceCounter, the results are not very stable.

My conclusion : The general application of timeGetTime is fully sufficient, the accuracy is adjusted to 1 milliseconds, most of the situation is sufficient. System.Diagnostics.Stopwatch is also recommended because it is convenient to call.

A little bit of precision timing in C #

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.