Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
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.
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.
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
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
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
Output:
The Stopwatch
class offers several advanced features beyond basic time measurement. Let's explore some of these features:
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
Output:
IsHighResolution
PropertyThe 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
Output:
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
Output:
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
Output:
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
To start using IronPDF in your C# application, follow these simple steps:
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
Alternatively, you can use the IronPDF NuGet Package Page to download and install the "IronPdf" package.
Reference in Code: After successful installation, add a reference to IronPDF in your C# code:
using IronPdf;
using IronPdf;
Imports IronPdf
Now, you're ready to leverage the capabilities of IronPDF in your application.
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
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:
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.
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.
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.
The Elapsed property of the Stopwatch class provides the total elapsed time measured by the stopwatch as a TimeSpan object.
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.
Yes, Stopwatch supports high-resolution timing if the underlying system provides it, which can be checked using the IsHighResolution property.
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.
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.
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.