Visual Basic StopWatch/Timer Wrong?

jonthedit

Well-Known Member
OP
Member
Joined
May 30, 2011
Messages
1,682
Trophies
0
XP
1,010
Country
Bangladesh
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
Code:
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()
        'checknoteintegrity()
        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
        Timer2.Start()
        sw.Start()
        Threading.Thread.Sleep(1000)
    End Sub
End Class
Ignore some of the bits about key presses, not needed for now.

download:
https://mega.co.nz/#!RYB1zYbL!tNFtg9kWojt1ASKzKYjRj8uDPKe3JnlL1T6VQpvXA3Q

alt download
http://s000.tinyupload.com/index.php?file_id=95210156442717472759
 

daxtsu

Well-Known Member
Member
Joined
Jun 9, 2007
Messages
5,627
Trophies
2
XP
5,194
Country
Antarctica
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 vb.net) 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.
 
  • Like
Reactions: jonthedit

Site & Scene News

Popular threads in this forum

General chit-chat
Help Users
  • No one is chatting at the moment.
    Psionic Roshambo @ Psionic Roshambo: https://www.youtube.com/watch?v=iIpfWORQWhU