Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

vb.net - Accurate Windows timer? System.Timers.Timer() is limited to 15 msec

I need an accurate timer to interface a Windows application to a piece of lab equipment.

I used System.Timers.Timer() to create a timer that ticks every 10 msec, but this clock runs slow. For example 1000 ticks with an interval of 10 msec should take 10 wall-clock seconds, but it actually takes more like 20 wall-clock sec (on my PC). I am guessing this is because System.Timers.Timer() is an interval timer that is reset every time it elapses. Since it will always take some time between when the timer elapses and when it is reset (to another 10msec) the clock will run slow. This probably fine if the interval is large (seconds or minutes) but unacceptable for very short intervals.

Is there a function on Windows that will trigger a procedure every time the system clock crosses a 10 msec (or whatever) boundary?

This is a simple console application.

Thanks

Norm

UPDATE: System.Timers.Timer() is extremely inaccurate for small intervals.

I wrote a simple program that counted 10 seconds several ways:

Interval=1, Count=10000, Run time = 160 sec, msec per interval=16

Interval=10, Count=1000, Run time = 16 sec, msec per interval=15

Interval=100, Count=100, Run time = 11 sec, msec per interval=110

Interval=1000, Count=10, Run time = 10 sec, msec per interval=1000

It seems like System.Timers.Timer() cannot tick faster that about 15 msec, regardless of the interval setting.

Note that none of these tests seemed to use any measurable CPU time, so the limit is not the CPU, just a .net limitation (bug?)

For now I think I can live with an inaccurate timer that triggers a routine every 15 msec or so and the routine gets an accurate system time. Kinda strange, but...

I also found a shareware product ZylTimer.NET that claims to be a much more accurate .net timer (resolution of 1-2 msec). This may be what I need. If there is one product there are likely others.

Thanks again.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to use a high resolution timer such as QueryPerformanceCounter


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...