Click here to Skip to main content
15,894,539 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was creating some very basic time routines to do some testing when I ended up with some very unexpected output.

My code was a simple console app:

VB
Imports System.Threading

Module Module1
    Sub Main()
        Dim StartTime As DateTime
        Dim EndTime As DateTime

        For i As Integer = 1 To 10
            StartTime = DateTime.Now
            Thread.Sleep(5)
            EndTime = DateTime.Now
            Console.WriteLine(EndTime.Millisecond - StartTime.Millisecond)
        Next
        Console.ReadLine()
    End Sub
End Module


but the output was:

5
5
5
-995
5
5
5
5
5
5

The 5's (and even the occassional 6) were expected ... the -995 wasn't.

Can anyone explain what would have caused the system to generate that as an output?

Thanks.
Posted

Because sometimes, the StartTime.Millisecond = 995, and the EndTime.Millisecond is 0.

What you REALLY want to do is this:

VB
Console.WriteLine((EndTime - StartTime).TotalMilliseconds)
 
Share this answer
 
v2
Comments
BHort 13-Sep-11 11:07am    
Excellent. Thank you for that. I've been programming for 30 years but I'm still fairly new to VB.Net
#realJSOP 13-Sep-11 11:10am    
Actually, it's the .Net framework that you're unfamiliar with. If it helps lessen the pain, I suffered from (and still do to some extent) the same thing when I moved from unmanaged C++/MFC to .Net.
BHort 13-Sep-11 11:21am    
I stand corrected. I figure I'm surviving ... so I'm not really worried about it but I do appreciate people who are willing to contribute a constructive criticism once in a while. Thanks again.
I think I figured it out just after hitting submit.

Because I'm only doing the math on the millisecond portion it will sometimes have .995 as the start time and then wrap to .000 for the end time (or variations between .995 - .999) ... and thus give the negative result.

Interesting.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900