Skip to footer content
.NET HELP

C# Stopwatch (How It Works For Developers)

In the vast landscape of programming languages, C# stands out as a versatile and powerful language used for developing a wide range of applications, from desktops to web and mobile applications. One of the key features that make C# a favorite among developers is its rich set of libraries and classes, providing solutions to various programming challenges. Among these, the Stopwatch class holds a special place for its role in accurate time measurement, profiling, and performance analysis.

In this article, we will see how to use the Stopwatch object in C# to find the time taken to perform a specific task using the public TimeSpan Elapsed property. Also, we will time the total elapsed time measured for the PDF creation using IronPDF for C# Developers.

1. What is the Stopwatch Class?

The Stopwatch class is part of the System.Diagnostics namespace in C#, and provides a simple and efficient way to measure elapsed time with high precision. It was introduced with the .NET Framework and has been a valuable tool for developers in tracking the execution time of code segments, optimizing performance, and profiling applications.

2. Initialization and Basic Usage

Using the Stopwatch class is straightforward. To start using it, you first need to create a new instance of the Stopwatch class:

using System.Diagnostics;

class Program
{
    static void Main()
    {
        // Create a new stopwatch instance for timing operations
        Stopwatch stopwatch = new Stopwatch();
    }
}
using System.Diagnostics;

class Program
{
    static void Main()
    {
        // Create a new stopwatch instance for timing operations
        Stopwatch stopwatch = new Stopwatch();
    }
}
Imports System.Diagnostics

Friend Class Program
	Shared Sub Main()
		' Create a new stopwatch instance for timing operations
		Dim stopwatch As New Stopwatch()
	End Sub
End Class
$vbLabelText   $csharpLabel

Once the Stopwatch instance is created, you can start and stop the stopwatch to measure elapsed time:

using System;

class Program
{
    static void Main()
    {
        Stopwatch stopwatch = new Stopwatch();

        // Start timing
        stopwatch.Start();
        Console.WriteLine("It will measure the time between start and stop");

        // Stop timing
        stopwatch.Stop();
    }
}
using System;

class Program
{
    static void Main()
    {
        Stopwatch stopwatch = new Stopwatch();

        // Start timing
        stopwatch.Start();
        Console.WriteLine("It will measure the time between start and stop");

        // Stop timing
        stopwatch.Stop();
    }
}
Imports System

Friend Class Program
	Shared Sub Main()
		Dim stopwatch As New Stopwatch()

		' Start timing
		stopwatch.Start()
		Console.WriteLine("It will measure the time between start and stop")

		' Stop timing
		stopwatch.Stop()
	End Sub
End Class
$vbLabelText   $csharpLabel

The elapsed time can be obtained using the Elapsed property:

using System;

class Program
{
    static void Main()
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        // Simulate some work by sleeping for 2 seconds
        System.Threading.Thread.Sleep(2000);

        // Stop timing
        stopwatch.Stop();

        // Fetch the elapsed time
        TimeSpan elapsed = stopwatch.Elapsed;
        Console.WriteLine($"Elapsed time: {elapsed}");
    }
}
using System;

class Program
{
    static void Main()
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        // Simulate some work by sleeping for 2 seconds
        System.Threading.Thread.Sleep(2000);

        // Stop timing
        stopwatch.Stop();

        // Fetch the elapsed time
        TimeSpan elapsed = stopwatch.Elapsed;
        Console.WriteLine($"Elapsed time: {elapsed}");
    }
}
Imports System

Friend Class Program
	Shared Sub Main()
		Dim stopwatch As New Stopwatch()
		stopwatch.Start()

		' Simulate some work by sleeping for 2 seconds
		System.Threading.Thread.Sleep(2000)

		' Stop timing
		stopwatch.Stop()

		' Fetch the elapsed time
		Dim elapsed As TimeSpan = stopwatch.Elapsed
		Console.WriteLine($"Elapsed time: {elapsed}")
	End Sub
End Class
$vbLabelText   $csharpLabel

Output:

C# Stopwatch (How It Works For Developers): Figure 1 - System Timer Output

3. Advanced Features of the Stopwatch

The Stopwatch class offers several advanced features beyond basic time measurement. Let's explore some of these features:

3.1. Restart Method

The Restart method is a convenient way to stop and reset the elapsed time to zero in a single operation. This can be useful when measuring the execution time of multiple code segments without creating a new Stopwatch instance.

using System;

class Program
{
    static void Main()
    {
        Stopwatch stopwatch = new Stopwatch();

        // Start timing
        stopwatch.Start();
        Console.WriteLine("The time will restart after executing the below code");

        // Restart timing
        stopwatch.Restart();

        // Simulate work
        System.Threading.Thread.Sleep(1000);

        // Stop timing
        stopwatch.Stop();

        // Fetch the elapsed time after restart
        TimeSpan elapsed = stopwatch.Elapsed;
        Console.WriteLine($"Total Elapsed time after Restart: {elapsed}");
    }
}
using System;

class Program
{
    static void Main()
    {
        Stopwatch stopwatch = new Stopwatch();

        // Start timing
        stopwatch.Start();
        Console.WriteLine("The time will restart after executing the below code");

        // Restart timing
        stopwatch.Restart();

        // Simulate work
        System.Threading.Thread.Sleep(1000);

        // Stop timing
        stopwatch.Stop();

        // Fetch the elapsed time after restart
        TimeSpan elapsed = stopwatch.Elapsed;
        Console.WriteLine($"Total Elapsed time after Restart: {elapsed}");
    }
}
Imports System

Friend Class Program
	Shared Sub Main()
		Dim stopwatch As New Stopwatch()

		' Start timing
		stopwatch.Start()
		Console.WriteLine("The time will restart after executing the below code")

		' Restart timing
		stopwatch.Restart()

		' Simulate work
		System.Threading.Thread.Sleep(1000)

		' Stop timing
		stopwatch.Stop()

		' Fetch the elapsed time after restart
		Dim elapsed As TimeSpan = stopwatch.Elapsed
		Console.WriteLine($"Total Elapsed time after Restart: {elapsed}")
	End Sub
End Class
$vbLabelText   $csharpLabel

Output:

C# Stopwatch (How It Works For Developers): Figure 2 - Restart Output

3.2. IsHighResolution Property

The IsHighResolution property indicates whether the underlying timing mechanism is based on a high-resolution performance counter to accurately measure elapsed time. Checking this property can be useful when dealing with systems that may not support high-resolution timing methods.

using System;

class Program
{
    static void Main()
    {
        if (Stopwatch.IsHighResolution)
        {
            Console.WriteLine("High-resolution timing is supported");
        }
        else
        {
            Console.WriteLine("Fallback to lower-resolution timing");
        }
    }
}
using System;

class Program
{
    static void Main()
    {
        if (Stopwatch.IsHighResolution)
        {
            Console.WriteLine("High-resolution timing is supported");
        }
        else
        {
            Console.WriteLine("Fallback to lower-resolution timing");
        }
    }
}
Imports System

Friend Class Program
	Shared Sub Main()
		If Stopwatch.IsHighResolution Then
			Console.WriteLine("High-resolution timing is supported")
		Else
			Console.WriteLine("Fallback to lower-resolution timing")
		End If
	End Sub
End Class
$vbLabelText   $csharpLabel

Output:

C# Stopwatch (How It Works For Developers): Figure 3 - High Resolution Timing Output

3.3. Frequency Property

The Frequency property returns the frequency of the underlying timer in ticks per second. This value is useful for converting elapsed ticks to other time units, such as milliseconds.

using System;

class Program
{
    static void Main()
    {
        long frequency = Stopwatch.Frequency;
        Console.WriteLine($"Timer Frequency: {frequency} ticks per second");
    }
}
using System;

class Program
{
    static void Main()
    {
        long frequency = Stopwatch.Frequency;
        Console.WriteLine($"Timer Frequency: {frequency} ticks per second");
    }
}
Imports System

Friend Class Program
	Shared Sub Main()
		Dim frequency As Long = Stopwatch.Frequency
		Console.WriteLine($"Timer Frequency: {frequency} ticks per second")
	End Sub
End Class
$vbLabelText   $csharpLabel

Output:

C# Stopwatch (How It Works For Developers): Figure 4 - Frequency Output

3.4. ElapsedTicks Property

The ElapsedTicks property provides direct access to the raw tick count without the need to convert it to time units. This can be beneficial when performing custom calculations or dealing with low-level timing requirements.

using System;

class Program
{
    static void Main()
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        // Simulate some work
        System.Threading.Thread.Sleep(1500);

        // Stop timing
        stopwatch.Stop();

        // Fetch the elapsed ticks
        long elapsedTicks = stopwatch.ElapsedTicks;
        Console.WriteLine($"Elapsed Ticks: {elapsedTicks}");
    }
}
using System;

class Program
{
    static void Main()
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        // Simulate some work
        System.Threading.Thread.Sleep(1500);

        // Stop timing
        stopwatch.Stop();

        // Fetch the elapsed ticks
        long elapsedTicks = stopwatch.ElapsedTicks;
        Console.WriteLine($"Elapsed Ticks: {elapsedTicks}");
    }
}
Imports System

Friend Class Program
	Shared Sub Main()
		Dim stopwatch As New Stopwatch()
		stopwatch.Start()

		' Simulate some work
		System.Threading.Thread.Sleep(1500)

		' Stop timing
		stopwatch.Stop()

		' Fetch the elapsed ticks
		Dim elapsedTicks As Long = stopwatch.ElapsedTicks
		Console.WriteLine($"Elapsed Ticks: {elapsedTicks}")
	End Sub
End Class
$vbLabelText   $csharpLabel

Output:

C# Stopwatch (How It Works For Developers): Figure 5 - Elapsed Ticks Output

4. Introduction to IronPDF in C#

IronPDF is a powerful C# library that allows developers to effortlessly create, manipulate, and process PDF documents within their .NET applications. Whether you need to generate PDFs from HTML, images, or other formats, IronPDF provides a comprehensive set of tools for seamless integration into your C# projects.

IronPDF offers the unique ability to convert HTML to PDF, keeping layouts and styles intact. This feature is ideal for creating PDFs from web content, such as reports, invoices, or documentation. You can convert HTML files, URLs, and HTML strings into PDF files.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        // Initialize the PDF renderer
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        // Initialize the PDF renderer
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Initialize the PDF renderer
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

4.1. Installation of IronPDF in C#

To start using IronPDF in your C# application, follow these simple steps:

  1. NuGet Package Manager: Open your C# project in Visual Studio and navigate to the Package Manager Console. Execute the following command to install IronPDF:

    Install-Package IronPdf
    Install-Package IronPdf
    SHELL

    Alternatively, you can use the IronPDF NuGet Package Page to download and install the "IronPdf" package.

  2. Reference in Code: After successful installation, add a reference to IronPDF in your C# code:

    using IronPdf;
    using IronPdf;
    Imports IronPdf
    $vbLabelText   $csharpLabel

    Now, you're ready to leverage the capabilities of IronPDF in your application.

4.2. Using C# Stopwatch to Time PDF Creation from URL

Now, let's demonstrate how to use C#'s Stopwatch class to measure the time taken to create a PDF from a URL using IronPDF:

using System;
using System.Diagnostics;
using IronPdf;

class Program
{
    static void Main()
    {
        // Initialize IronPDF Renderer
        IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();

        // Specify the URL for PDF generation
        string urlToConvert = "https://example.com";

        // Use Stopwatch to measure the time taken
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        // Create PDF from URL
        PdfDocument PDF = Renderer.RenderUrlAsPdf(urlToConvert);

        // Stop measuring elapsed time
        stopwatch.Stop();

        // Save the generated PDF to a file
        PDF.SaveAs("GeneratedPDF.pdf");

        // Display the time taken
        Console.WriteLine($"Time taken to create PDF from URL: {stopwatch.ElapsedMilliseconds} milliseconds");
    }
}
using System;
using System.Diagnostics;
using IronPdf;

class Program
{
    static void Main()
    {
        // Initialize IronPDF Renderer
        IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();

        // Specify the URL for PDF generation
        string urlToConvert = "https://example.com";

        // Use Stopwatch to measure the time taken
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        // Create PDF from URL
        PdfDocument PDF = Renderer.RenderUrlAsPdf(urlToConvert);

        // Stop measuring elapsed time
        stopwatch.Stop();

        // Save the generated PDF to a file
        PDF.SaveAs("GeneratedPDF.pdf");

        // Display the time taken
        Console.WriteLine($"Time taken to create PDF from URL: {stopwatch.ElapsedMilliseconds} milliseconds");
    }
}
Imports System
Imports System.Diagnostics
Imports IronPdf

Friend Class Program
	Shared Sub Main()
		' Initialize IronPDF Renderer
		Dim Renderer As New IronPdf.HtmlToPdf()

		' Specify the URL for PDF generation
		Dim urlToConvert As String = "https://example.com"

		' Use Stopwatch to measure the time taken
		Dim stopwatch As New Stopwatch()
		stopwatch.Start()

		' Create PDF from URL
		Dim PDF As PdfDocument = Renderer.RenderUrlAsPdf(urlToConvert)

		' Stop measuring elapsed time
		stopwatch.Stop()

		' Save the generated PDF to a file
		PDF.SaveAs("GeneratedPDF.pdf")

		' Display the time taken
		Console.WriteLine($"Time taken to create PDF from URL: {stopwatch.ElapsedMilliseconds} milliseconds")
	End Sub
End Class
$vbLabelText   $csharpLabel

This example initializes IronPDF, uses the HtmlToPdf class to render a PDF from a specified URL, and measures the time taken using Stopwatch. Adjust the urlToConvert variable with the desired URL, and you can further customize the PDF creation process as needed for your application.

Output:

C# Stopwatch (How It Works For Developers): Figure 6 - PDF Creation Timer Output

5. Conclusion

In conclusion, the Stopwatch class in C# stands as a pivotal tool for accurate time measurement and performance analysis, offering developers the means to optimize code and assess operational efficiency. Its intuitive interface and advanced features make it versatile for various timing requirements. Additionally, the integration of IronPDF into C# projects expands the language's capabilities in PDF document manipulation, providing a seamless solution for generating, modifying, and processing PDFs.

The demonstrated example of using Stopwatch to measure the time taken to create a PDF from a URL with IronPDF showcases the synergy between precise time tracking and advanced libraries, highlighting the significance of meticulous timing in assessing application performance. Together, C#'s Stopwatch and IronPDF empower developers to build high-performance applications with meticulous timing and versatile PDF handling capabilities.

To get your free trial license to test IronPDF functionality, visit the IronPDF Licensing Information Page. The complete tutorial on URL to PDF conversion can be found on the IronPDF URL to PDF Tutorial.

Frequently Asked Questions

What is the purpose of a timing class in C#?

The Stopwatch class in C# is used for measuring elapsed time with high precision, which is useful for tracking code execution time, optimizing performance, and profiling applications.

How do you start and stop a timing object in C#?

To start and stop a Stopwatch, you first create an instance of the Stopwatch class, then call the Start() method to begin timing and the Stop() method to end timing.

What is the Elapsed property in a timing class?

The Elapsed property of the Stopwatch class provides the total elapsed time measured by the stopwatch as a TimeSpan object.

What is the Restart method in a timing class?

The Restart method stops the current timing session and resets the elapsed time to zero, allowing you to start a new timing session without creating a new Stopwatch instance.

Does a timing object support high-resolution timing?

Yes, Stopwatch supports high-resolution timing if the underlying system provides it, which can be checked using the IsHighResolution property.

What is a PDF library and how is it used in C#?

IronPDF is a C# library used for creating, manipulating, and processing PDF documents. It allows developers to convert HTML, URLs, and other formats into PDFs seamlessly within .NET applications.

How can you time the creation of a PDF from a URL using a timing object in C#?

To time PDF creation from a URL, initialize a Stopwatch before starting the PDF rendering process and stop it once the process is complete. The elapsed time can then be obtained to see how long the process took.

How do you install a PDF library in a C# project?

You can install IronPDF in a C# project using the NuGet Package Manager in Visual Studio by running the command 'Install-Package IronPdf'. After installation, add 'using IronPdf;' to your code.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.