My application needs to time some realtime events down to the
millisecond range. It seems that Thread.Sleep only gives a
10-millisecond resolution. I also believe that DateTime.Now() only
returns the time to the nearest 10-millisecond boundary -- despite the
documentation that indicates DateTime records an instant in time down to
the Tick level. This does not appear to be a problem with
System.Windows.Forms.Timer, as I can produce accurate delays with it.

The following test code snippet demonstrates the Thread.Sleep problem:

Dim I As Integer, Sample(20) As DateTime
For I = 0 To UBound(Sample)
    System.Threading.Thread.Sleep(I * 3)
    Sample(I) = DateTime.Now()
Next
For I = 1 To UBound(Sample)
    Console.WriteLine("Sample({0}) = {1}, Interval = {2} ms", _
        I, Format(Sample(I), "hh:mm:ss.fffff"),
Sample(I).Subtract(Sample(I - 1)).TotalMilliseconds)
Next

The output is:

Sample(1) = 11:59:50.34376, Interval = 10.0144 ms
Sample(2) = 11:59:50.35378, Interval = 10.0144 ms
Sample(3) = 11:59:50.36379, Interval = 10.0144 ms
Sample(4) = 11:59:50.38382, Interval = 20.0288 ms
Sample(5) = 11:59:50.40385, Interval = 20.0288 ms
Sample(6) = 11:59:50.42388, Interval = 20.0288 ms
Sample(7) = 11:59:50.45392, Interval = 30.0432 ms
Sample(8) = 11:59:50.48396, Interval = 30.0432 ms
Sample(9) = 11:59:50.51401, Interval = 30.0432 ms
Sample(10) = 11:59:50.54405, Interval = 30.0432 ms
Sample(11) = 11:59:50.58411, Interval = 40.0576 ms
Sample(12) = 11:59:50.62417, Interval = 40.0576 ms
Sample(13) = 11:59:50.66422, Interval = 40.0576 ms
Sample(14) = 11:59:50.71430, Interval = 50.072 ms
Sample(15) = 11:59:50.76437, Interval = 50.072 ms
Sample(16) = 11:59:50.81444, Interval = 50.072 ms
Sample(17) = 11:59:50.87453, Interval = 60.0864 ms
Sample(18) = 11:59:50.93461, Interval = 60.0864 ms
Sample(19) = 11:59:50.99470, Interval = 60.0864 ms
Sample(20) = 11:59:51.05479, Interval = 60.0864 ms

Can anybody shed some light on this problem? Thanks.

Richard J. Kucia
Owner, Kucia Associates

You can read messages from the DOTNET archive, unsubscribe from DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

Reply via email to