Reputation: 25
So I want to make a timer that does this: each time I click the button this happens:
0.052
0.521
1.621
2.151
...
But instead of that it goes like this:
0.015
0.032
0.112
0.252
...
This is happening: picture
This code is not correct, I waits a long time until it makes a sec..
int sec = 0, ms = 1;
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
listBox1.Items.Add(label1.Text);
timer1.Interval = 1;
}
private void timer1_Tick(object sender, EventArgs e)
{
ms++;
if (ms >= 1000)
{
sec++;
ms = 0;
}
label1.Text = String.Format("{0:0}.{1:000}", sec, ms);
}
Upvotes: 1
Views: 4677
Reputation: 6174
You should use a Stopwatch object from the System.Diagnostics namespace of the .Net framework. Like this:
System.Diagnostics.Stopwatch sw = new Stopwatch();
public void button1_Click()
{
sw.Start; // start the stopwatch
// do work
...
sw.Stop; // stop the stopwatch
// display stopwatch contents
label1.Text = string.Format({0}, sw.Elapsed);
}
If you want to see the total time elapsed as total seconds and milliseconds only (no minutes or hours), you can change that final line to:
label1.Text = string.Format({0}, sw.ElapsedMilliseconds / 1000.0)
Upvotes: 4