Visual Basic StopWatch/Timer Wrong?

Discussion in 'Computer Programming, Emulation, and Game Modding' started by jonthedit, Feb 17, 2015.

  1. jonthedit

    jonthedit GBAtemp Advanced Maniac

    May 30, 2011
    Hi, not sure how this possible but a stopwatch set to 1000
    and a timer set to go up 1 second are actually not perfectly in sync!
    I know VB is horrible, but for this project it will work fine.
    Here is the code and the .exe
    Public Class Form1
        Public hit2 As Boolean
        Dim fg As Integer
        Dim songtime As Double
        Dim sw As New Stopwatch
        Private Sub Form1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
            'If Not e.Control Then Exit Sub
            Select Case e.KeyCode
                Case Keys.D : HitRight()
                Case Keys.A : HitLeft()
            End Select
        End Sub
        Public Sub HitRight()
            LabelLeft.Text = sw.ElapsedMilliseconds
        End Sub
        Public Sub HitLeft()
            LabelLeft.Text = Format(songtime, "0.00")
        End Sub
        Private Sub Timer2_Tick_1(sender As Object, e As EventArgs) Handles Timer2.Tick
            fg = fg + 1
            LabelRight.Text = fg.ToString
            LabelLeft.Text = sw.ElapsedMilliseconds
        End Sub
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        End Sub
    End Class
    Ignore some of the bits about key presses, not needed for now.


    alt download
  2. daxtsu

    daxtsu GBAtemp Guru

    Jun 9, 2007
    There are several problems here:

    1. That's not the entire source code, so it won't compile as it is (where are your using (import in directives?).
    2. Timers (both System.Windows.Forms.Timer and the Stopwatch class) don't need a Sleep function to be called for them, they run when the OS schedules them to, and using Sleep is generally considered bad practice as far as I know.
    3. System.Windows.Forms.Timer uses a very inacccurate timer (it can be out of touch with reality by up to +/- 100milliseconds if I recall, so it's not very accurate), while Stopwatch uses the high precision timer available to Windows, so it's not really a surprise if they aren't in perfect sync.
    jonthedit likes this.
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice