.NET HELP

C# Stopwatch (How It Works For Developers)

Published January 27, 2024
Share:

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 C#.

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()
    {
        Stopwatch stopwatch = new Stopwatch(); // Stopwatch object
    }
}
using System.Diagnostics;

class Program
{
    static void Main()
    {
        Stopwatch stopwatch = new Stopwatch(); // Stopwatch object
    }
}
Imports System.Diagnostics

Friend Class Program
	Shared Sub Main()
		Dim stopwatch As New Stopwatch() ' Stopwatch object
	End Sub
End Class
VB   C#

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

stopwatch.Start();
Console.WriteLine("It will measure the time between start and stop");
stopwatch.Stop(); // Stop measuring elapsed time
stopwatch.Start();
Console.WriteLine("It will measure the time between start and stop");
stopwatch.Stop(); // Stop measuring elapsed time
stopwatch.Start()
Console.WriteLine("It will measure the time between start and stop")
stopwatch.Stop() ' Stop measuring elapsed time
VB   C#

The elapsed time can be obtained using the Elapsed property:

TimeSpan elapsed = stopwatch.Elapsed;
Console.WriteLine($"Elapsed time: {elapsed}");
TimeSpan elapsed = stopwatch.Elapsed;
Console.WriteLine($"Elapsed time: {elapsed}");
Dim elapsed As TimeSpan = stopwatch.Elapsed
Console.WriteLine($"Elapsed time: {elapsed}")
VB   C#

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.

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Console.WriteLine("The time will restart after executing the below code");
stopwatch.Restart(); 
stopwatch.Stop();
TimeSpan elapsed = stopwatch.Elapsed;
Console.WriteLine($"Total Elapsed time after Restart: {elapsed}");
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Console.WriteLine("The time will restart after executing the below code");
stopwatch.Restart(); 
stopwatch.Stop();
TimeSpan elapsed = stopwatch.Elapsed;
Console.WriteLine($"Total Elapsed time after Restart: {elapsed}");
Dim stopwatch As New Stopwatch()
stopwatch.Start()
Console.WriteLine("The time will restart after executing the below code")
stopwatch.Restart()
stopwatch.Stop()
Dim elapsed As TimeSpan = stopwatch.Elapsed
Console.WriteLine($"Total Elapsed time after Restart: {elapsed}")
VB   C#

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.

Stopwatch stopwatch = new Stopwatch();
if (Stopwatch.IsHighResolution)
{
    Console.WriteLine("High-resolution timing is supported");
}
else
{
    Console.WriteLine("Fallback to lower-resolution timing");
}
Stopwatch stopwatch = new Stopwatch();
if (Stopwatch.IsHighResolution)
{
    Console.WriteLine("High-resolution timing is supported");
}
else
{
    Console.WriteLine("Fallback to lower-resolution timing");
}
Dim stopwatch As New Stopwatch()
If System.Diagnostics.Stopwatch.IsHighResolution Then
	Console.WriteLine("High-resolution timing is supported")
Else
	Console.WriteLine("Fallback to lower-resolution timing")
End If
VB   C#

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.

Stopwatch stopwatch = new Stopwatch();
long frequency = Stopwatch.Frequency;
Console.WriteLine($"Timer Frequency: {frequency} ticks per second");
Stopwatch stopwatch = new Stopwatch();
long frequency = Stopwatch.Frequency;
Console.WriteLine($"Timer Frequency: {frequency} ticks per second");
Dim stopwatch As New Stopwatch()
Dim frequency As Long = System.Diagnostics.Stopwatch.Frequency
Console.WriteLine($"Timer Frequency: {frequency} ticks per second")
VB   C#

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.

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// Code segment
long elapsedTicks = stopwatch.ElapsedTicks;
Console.WriteLine($"Elapsed Ticks: {elapsedTicks}");
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// Code segment
long elapsedTicks = stopwatch.ElapsedTicks;
Console.WriteLine($"Elapsed Ticks: {elapsedTicks}");
Dim stopwatch As New Stopwatch()
stopwatch.Start()
' Code segment
Dim elapsedTicks As Long = stopwatch.ElapsedTicks
Console.WriteLine($"Elapsed Ticks: {elapsedTicks}")
VB   C#

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)
    {
        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)
    {
        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)
		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
VB   C#

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

    Alternatively, you can use the NuGet Package Website 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
    VB   C#

    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
        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 or perform other actions
        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
        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 or perform other actions
        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
		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 or perform other actions
		PDF.SaveAs("GeneratedPDF.pdf")
		' Display the time taken
		Console.WriteLine($"Time taken to create PDF from URL: {stopwatch.ElapsedMilliseconds} milliseconds")
	End Sub
End Class
VB   C#

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 license page. The complete tutorial on URL to PDF conversion can be found here.

< PREVIOUS
Jquery Datatable (How It Works For Developers)
NEXT >
Swashbuckle ASP .NET Core (How It Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >