Friday, January 6, 2012

How to create Stop Watch application in WPF?



Dotnet provides StopWatch class to measure elapsed execution time. Stopwatch is available in System.Diagnostics namespace. Stopwatch provides Start and Stop method to start/stop stopwatch. IsRunning property returns true or false based on stopwatch instance is running or not. It also provides Elapsed and ElapsedMilliseconds to get execution time. We can clear elapsed time by calling Reset method on stopwatch instance.

Let’s have a look on below code.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="0.3*"/>
        <RowDefinition Height="0.2*"/>
        <RowDefinition Height="0.5*"/>
    </Grid.RowDefinitions>
    <TextBlock Name="ClockTextBlock"
                TextAlignment="Center"
                VerticalAlignment="Center"
                FontSize="35" Foreground="Red"
                Grid.ColumnSpan="4"
                Grid.Row="0" />
    <Button Content="Start"
            Name="StartButton"
            Grid.Row="1"
            Grid.Column="0"
            Width="60" Height="35"
            Click="StartButton_Click" />
    <Button Content="Add"
            Name="AddButton"
            Grid.Row="1"
            Grid.Column="1"
            Width="60" Height="35"
            Click="AddButton_Click" />
    <Button Content="Stop"
            Name="StopButton"
            Grid.Row="1"
            Grid.Column="2"
            Width="60" Height="35"
            Click="StopButton_Click" />
    <Button Content="Reset"
            Name="ResetButton"
            Grid.Row="1"
            Grid.Column="3"
            Width="60" Height="35"
            Click="ResetButton_Click" />
    <ListBox Name="TimeElapsedItems"
                Margin="5" Width="150"
                Grid.Row="2"
                Grid.ColumnSpan="4" />
</Grid>

public partial class StopWatchDemo : Window
{
    DispatcherTimer dt = new DispatcherTimer();
    Stopwatch stopWatch = new Stopwatch();
    string currentTime = string.Empty;
    public StopWatchDemo()
    {
        InitializeComponent();
        dt.Tick += new EventHandler(dt_Tick);
        dt.Interval = new TimeSpan(0, 0, 0, 0, 1);
    }

    void dt_Tick(object sender, EventArgs e)
    {
        if (stopWatch.IsRunning)
        {
            TimeSpan ts = stopWatch.Elapsed;
            currentTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
            ClockTextBlock.Text = currentTime;
        }
    }
    private void StartButton_Click(object sender, RoutedEventArgs e)
    {
        stopWatch.Start();
        dt.Start();
    }

    private void StopButton_Click(object sender, RoutedEventArgs e)
    {
        if (stopWatch.IsRunning)
            stopWatch.Stop();
    }

    private void AddButton_Click(object sender, RoutedEventArgs e)
    {
        TimeElapsedItems.Items.Add(currentTime);
    }

    private void ResetButton_Click(object sender, RoutedEventArgs e)
    {
        stopWatch.Reset();
        stopWatch.Start();
    }
}



As per above code, four button are added, Start, Stop, Reset and Add. Start will start the stopwatch and stop will stop the stopwatch. Reset will reset elapsed time to zero and Add button will add elapsed time of stopwatch to Listbox.

How to get execution time of code?

Stopwatch class used to examine execution time of code. We can efficiently find execution time of particular method or block of code. This is incredibly useful while performing diagnostics or performance analysis.

void MyMethod(object sender, RoutedEventArgs e)
{
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();

    for (int i = 0; i < 10000000; i++)
        Console.Write("");

    stopWatch.Stop();
           
    TimeSpan ts = stopWatch.Elapsed;
    Console.WriteLine(String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10));
}

Output
00:00:01.15

Above code examine total time to execute for loop. Just before starting for loop stopwatch is started and after completing for loop immediately stops stopwatch. It will find total time to execute this for loop.

See Also - 

3 comments:

  1. thank you for the great post. very understandable.

    ReplyDelete
  2. Thank you for your simple and understandable post. A little more complex, I just want to know if I am using a MVVM and trying to create a reusable Stop watch control where the duration for stop watch has to be provided by user of this control. I just need to bind the duration value of control just like we do for other controls(e.g.Text property of textbox control). If I use user control's view model as data context, I am having difficulties to do it. All in one that how to build user control having their own View Model and can get set their property from the xaml where they have been used.

    ReplyDelete