.NET 帮助

C# 计时器(它是如何为开发人员工作的)

发布 2024年一月27日
分享:

在种类繁多的编程语言中,C# 是一种通用且功能强大的语言,可用于开发从桌面到网络和移动应用程序等各种应用程序。C# 受到开发人员青睐的主要原因之一是它拥有丰富的库和类,可为各种编程难题提供解决方案。其中包括 秒表类 它在精确的时间测量、剖析和性能分析方面发挥着特殊的作用。

在本文中,我们将了解如何使用 C# 中的秒表对象,使用公共 TimeSpan Elapsed 属性查找执行特定任务所需的时间。此外,我们还将使用 IronPDF C#.

1.什么是秒表类?

Stopwatch "类是 C# 中 "System.Diagnostics "命名空间的一部分,它提供了一种简单而有效的方法来高精度地测量经过的时间。该类随 .NET Framework 一起引入,是开发人员跟踪代码段执行时间、优化性能和剖析应用程序的重要工具。

2.初始化和基本使用

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

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#

一旦创建了 "秒表 "实例,就可以启动和停止秒表来测量经过的时间:

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#

可使用 Elapsed 属性获取经过时间:

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#

输出:

C# 秒表(如何为开发人员工作):图 1 - 系统定时器输出

3.秒表的高级功能

除了基本的时间测量功能外,"秒表 "类还提供了一些高级功能。让我们来探索其中的一些功能:

3.1.重启方法

重启 "方法是一种方便的方法,可在一次操作中停止并将已用时间重置为零。这在测量多个代码段的执行时间时非常有用,无需创建新的 Stopwatch 实例。

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#

输出:

C# 秒表(如何为开发人员工作):图 2 - 重新启动输出

3.2.IsHighResolution` 属性

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

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#

输出:

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

3.3.频率属性

频率 "属性返回底层定时器的频率,单位为每秒刻度。该值有助于将经过的刻度转换为其他时间单位,如毫秒。

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#

输出:

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

3.4.ElapsedTicks 属性

通过 ElapsedTicks 属性,可以直接访问原始刻度计数,而无需将其转换为时间单位。这在执行自定义计算或处理低级计时要求时非常有用。

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#

输出:

C# 秒表(如何为开发人员工作):图 5 - 已用计时器输出

4. IronPDF 在 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)
    {
        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.在 C&num 中安装 IronPDF;

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

  1. NuGet 软件包管理器:在 Visual Studio 中打开 C# 项目并导航至软件包管理器控制台。执行以下命令安装 IronPDF:
   Install-Package IronPdf

或者,您也可以使用 NuGet 软件包网站 下载并安装 "IronPdf "软件包。

  1. 代码中的引用:安装成功后,在 C# 代码中添加对 IronPDF 的引用:
   using IronPdf;
   using IronPdf;
Imports IronPdf
VB   C#

现在,您已经准备好在您的应用程序中利用 IronPDF 的功能了。

4.2.使用 C# 秒表为从 URL 创建 PDF 计时

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

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#

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

输出:

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

5.结论

总之,C# 中的 Stopwatch 类是精确测量时间和分析性能的关键工具,为开发人员提供了优化代码和评估运行效率的手段。其直观的界面和先进的功能使其成为满足各种计时要求的通用工具。此外,IronPDF 与 C# 项目的集成扩展了该语言在 PDF 文档处理方面的功能,为生成、修改和处理 PDF 提供了无缝解决方案。

使用 "Stopwatch "测量 IronPDF 从 URL 创建 PDF 所需的时间的示例展示了精确时间跟踪与高级库之间的协同作用,突出了在评估应用程序性能时精确计时的重要性。C# 的 Stopwatch 和 IronPDF 共同赋予了开发人员构建高性能应用程序的能力,使其具备细致的计时和多功能 PDF 处理能力。

要获取免费试用许可证以测试 IronPDF 功能,请访问 许可证页面.有关 URL 转换为 PDF 的完整教程可参见 这里.

< 前一页
Jquery Datatable(开发人员的工作原理)
下一步 >
Swashbuckle ASP .NET Core(它如何为开发人员工作)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >