跳至页脚内容
.NET 帮助

C# Stopwatch(开发者如何使用)

在广阔的编程语言领域中,C# 是一门多功能且强大的语言,适用于从桌面应用到 Web 和移动应用的各类开发场景。 C# 深受开发人员青睐的关键原因之一,是其丰富的库和类集合,能够解决各种编程挑战。 其中,Stopwatch 类在精确计时、性能剖析和分析方面具有重要地位。

本文将介绍如何在 C# 中使用 Stopwatch 对象,通过公共 TimeSpan Elapsed 属性测量执行特定任务所需的时间。 此外,还将演示如何记录使用 IronPDF 创建 PDF 的总耗时。

1. 什么是 Stopwatch 类?

Stopwatch 类是 C# 中 System.Diagnostics 命名空间的一部分,它提供了一种简单高效的方式来高精度地测量经过的时间。 它随着 .NET Framework 的引入成为了一个开发人员的宝贵工具,用于跟踪代码段的执行时间,优化性能,以及对应用程序进行剖析。

2. 初始化和基本使用

使用 Stopwatch 类非常简单。 要开始使用它,首先需要创建一个新的 Stopwatch 类实例:

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

创建 Stopwatch 实例后,即可启动和停止秒表来测量经过的时间:

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

可以使用 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}");
    }
}
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

输出:

C# Stopwatch(它如何为开发人员工作):图1 - 系统计时器输出

3. Stopwatch 的高级功能

Stopwatch 类除了基本的计时功能外,还提供了几个高级功能。 让我们来探索这些功能的一些部分:

3.1. Restart 方法

Restart 方法是一种方便的方法,可以在一次操作中停止并将经过的时间重置为零。 当测量多个代码段的执行时间而不创建新的 Stopwatch 实例时,这非常有用。

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

输出:

C# Stopwatch(它如何为开发人员工作):图2 - 重启输出

3.2. IsHighResolution 属性

IsHighResolution 属性指示底层计时机制是否基于高分辨率性能计数器来精确测量经过的时间。 在处理可能不支持高分辨率计时的系统时,检查此属性非常有用。

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

输出:

C# Stopwatch(它如何为开发人员工作):图3 - 高分辨率定时输出

3.3. Frequency 属性

Frequency 属性返回底层计时器每秒滴答数的频率。 此值对于将经过的计数转换为其他时间单位(例如毫秒)很有用。

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

输出:

C# Stopwatch(它如何为开发人员工作):图4 - 频率输出

3.4. ElapsedTicks 属性

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}");
    }
}
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

输出:

C# Stopwatch(它如何为开发人员工作):图5 - 经过滴答数输出

4. Introduction to IronPDF in C#

IronPDF 是一个强大的 C# 库,允许开发人员在 .NET 应用程序中轻松创建、操作和处理 PDF 文档。 无论您是需要从 HTML、图像还是其他格式生成 PDF,IronPDF 都提供了一整套工具,便于无缝集成到您的 C# 项目中。

IronPDF 提供了将 HTML 转换为 PDF 的独特功能,保持布局和样式完整。 该功能非常适合从网络内容创建 PDF,如报告、发票或文档。 您可以将 HTML 文件、URL 和 HTML 字符串转换为 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");
    }
}
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#

要开始在 C# 应用程序中使用 IronPDF,请按照以下简单步骤进行:

  1. NuGet 包管理器:在 Visual Studio 中打开您的 C# 项目并导航到包管理器控制台。 执行以下命令以安装 IronPDF:

    Install-Package IronPdf

    或者,您可以使用 IronPDF NuGet 包页面 下载并安装 "IronPDF" 包。

2.代码引用:安装成功后,在 C# 代码中添加对 IronPDF 的引用:

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

现在,您可以在应用程序中利用 IronPDF 的功能。

4.2. 使用 C# Stopwatch 计时 URL 的 PDF 创建

现在,让我们演示如何使用 C# 的 Stopwatch 类来测量使用 IronPDF 从 URL 创建 PDF 所需的时间:

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

此示例初始化 IronPDF,使用 HtmlToPdf 类从指定的 URL 渲染 PDF,并使用 Stopwatch 测量所花费的时间。 使用所需的 URL 调整 urlToConvert 变量,您可以根据应用程序的需要进一步自定义 PDF 创建过程。

输出:

C# Stopwatch(它如何为开发人员工作):图6 - PDF 创建计时器输出

5. 结论

总之,C# 中的 Stopwatch 类是精确计时和性能分析的核心工具,为开发人员提供了优化代码、评估运行效率的有效手段。 其直观的接口和丰富的高级功能使其能够满足各种计时需求。 此外,将 IronPDF 集成到 C# 项目中,可扩展语言在 PDF 文档处理方面的能力,提供生成、修改和处理 PDF 的无缝解决方案。

使用 Stopwatch 测量 IronPDF 从 URL 创建 PDF 所需时间的示例,展示了精确的时间跟踪和高级库之间的协同作用,突显了在评估应用程序性能时进行精确计时的重要性。 C# 的 Stopwatch 和 IronPDF 携手合作,使开发人员能够构建具有精确计时和多功能 PDF 处理功能的高性能应用程序。

要获取免费试用许可以测试 IronPDF 功能,请访问 IronPDF 审核许可信息页面。 关于 URL 转 PDF 转换的完整教程可以在 IronPDF URL 转 PDF 教程 页面找到。

常见问题解答

Stopwatch 类如何帮助优化 C# 应用程序性能?

C# 中的 Stopwatch 类允许开发人员以高精度测量代码执行所花费的时间。通过跟踪经过的时间,开发人员可以识别性能瓶颈并优化代码以提高效率。

Stopwatch 类为 C# 开发人员提供了哪些高级功能?

Stopwatch 类提供了高级功能,例如用于重置并重新开始计时的 Restart 方法、用于检查系统计时精度的 IsHighResolution、用于计时频率的 Frequency,以及用于细化时间测量的 ElapsedTicks。

Stopwatch 类可以在所有系统上用于高分辨率计时吗?

如果系统硬件支持高分辨率计时,Stopwatch 类则支持。开发人员可以检查 IsHighResolution 属性以确定其系统是否允许高分辨率计时。

如何在 C# 应用程序中将 HTML 内容转换为 PDF?

您可以使用 IronPDF 在 C# 应用程序中将 HTML 内容转换为 PDF。IronPDF 保持 HTML 的布局和样式完整性,使其适合生成高质量的 PDF 文档,如报告和发票。

如何在 C# 中将 Stopwatch 与 PDF 生成结合使用?

要将 Stopwatch 与 PDF 生成结合使用,在使用 IronPDF 启动 PDF 渲染过程之前启动 Stopwatch。一旦 PDF 生成完毕,停止 Stopwatch 以测量整个过程所用时间。

在 Visual Studio C# 项目中安装 PDF 库的过程是什么?

在 Visual Studio 中,您可以使用 NuGet 包管理器安装 IronPDF。在包管理器控制台中执行命令 Install-Package IronPDF 并在代码中包含 using IronPDF; 以访问其功能。

Stopwatch 类为何对 C# 性能调优至关重要?

Stopwatch 类对性能调优至关重要,因为它提供了精确的计时功能,帮助开发人员测量和分析代码执行时间。这些信息对于识别缓慢操作和提高应用程序性能至关重要。

Jacob Mellor,Team Iron 的首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。

Jacob 拥有曼彻斯特大学土木工程一级荣誉工程学士学位(BEng)(1998-2001 年)。他的旗舰产品 IronPDF 和 Iron Suite for .NET 库在全球的 NuGet 安装量已超过 3000 万次,其基础代码继续为全球使用的开发人员工具提供动力。Jacob 拥有 25 年的商业经验和 41 年的编码专业知识,他一直专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。

钢铁支援团队

我们每周 5 天,每天 24 小时在线。
聊天
电子邮件
打电话给我