C# Program to Create a Stop Watch

This is a C# Program to create stop watch.

Problem Description

This C# Program Creates Stop Watch.

Problem Solution

Here the stop watch is created and the time for the printing function is calculated and they are displayed.

Program/Source Code

Here is source code of the C# Program to Create Stop Watch. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Create Stop Watch 
 */
using System;
using System.Diagnostics;
using System.Threading;
class Program
{
    static void Main()
    {
        // Create new stopwatch
        Stopwatch stopwatch = new Stopwatch();
        // Begin timing
        stopwatch.Start();        
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine("HI");
        }
        // Stop timing
        stopwatch.Stop();
        Console.WriteLine("Time Elapsed : {0}",
            stopwatch.Elapsed);
        Console.ReadLine();
    }
}
Program Explanation

This C# program is used to create stop watch, it will provide a set of methods and properties that to use accurately measure elapsed time. The Stopwatch() function is used to initialize a new instance of the Stopwatch class. The start() function is used to Starts, or resumes, measuring elapsed time for an interval.

advertisement
advertisement

Using for loop initialize the value of ‘i’ variable as 0 and check the value of ‘i’ variable is less than 10. If the condition is true then execute the iteration of loop. The Stop() function is used to stop measuring elapsed time for an interval.

Then stopwatch.Elapsed is used to get the total elapsed time measured by the current instance. Here the stop watch is created and using for loop the time for the printing function is calculated and prints the value.

Runtime Test Cases
 
HI
HI
HI
HI
HI
HI
HI
HI
HI
HI
Time Elapsed : 00:00:00.0015114

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

Note: Join free Sanfoundry classes at Telegram or Youtube
If you wish to look at all C# Programming examples, go to 1000 C# Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.