The exact number of milliseconds for the GetTickCount () function
Source: Internet
Author: User
GetTickCount () and GetCurrentTime () are both accurate to 55 ms (one tick is 55 ms ). To be accurate to milliseconds, use the timeGetTime function or the QueryPerformanceCounter function. For specific examples, refer to QA001022 "using high-precision timer in VC ++", QA001813 "how to implement accurate timing in Windows" and QA004842 "timeGetTime function delay inaccuracy ".
Operating system: Win2000
Programming tools: VB6
Problem: I used the timeGetTime function to create a latency function, as shown below:
Private Sub DelayTime (ByVal DelayNum As Long)
Dim StartTime As Double, TmpTime As Single
StartTime = timeGetTime
Do
TmpTime = timeGetTime
If TmpTime <StartTime Then StartTime = TmpTime
Loop Until (TmpTime-StartTime)> = DelayNum
End Sub
However, the delay is not accurate! Sometimes there is an error of 10 milliseconds! Is there a problem with my program? How to correct it?
Level: intermediate (Wang Hui)
Although the unit of return value for timeGetTime is 1 ms, its accuracy is only about 10 ms.
To improve the accuracy, you can use QueryPerformanceCounter and QueryPerformanceFrequency. These two functions are not supported in every system. For systems that support them, the accuracy is lower than 1 ms. Windows has a very high-precision timer in microseconds, but different systems have different timer frequencies, which may be related to hardware and operating systems. You can use the API function QueryPerformanceFrequency to obtain the timer frequency. You can use the API function QueryPerformanceCounter to obtain the current value of the timer. Based on the time to be delayed and the timer frequency, you can calculate the number of cycles of the time timer to be delayed. In the Loop, QueryPerformanceCounter is used to read the timer value without stopping until the cycle is completed after a specified number of cycles. This achieves the goal of high precision latency. For example:
Private Declare Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As Currency) As Long
Private Declare Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As Currency) As Long
'Delaynum is the number of milliseconds of latency
Private Sub DelayTime (ByVal DelayNum As Long)
Dim Ctr1, Ctr2, Freq As Currency
Dim Count As Double
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.