.NET 幫助

C# 計時器(它如何對開發者運作)

發佈 2024年1月27日
分享:

在廣闊的程式語言背景中,C# 脫穎而出,作為一種多功能且強大的語言,用於開發從桌面到網路和移動應用程式的各種應用程式。C# 受到開發人員喜愛的主要原因之一是其豐富的庫和類別集,提供針對各類程式設計挑戰的解決方案。在這些庫中, 秒表類別 在準確時間測量、剖析和性能分析中具有特殊地位。

在本文中,我們將看到如何在 C# 中使用 Stopwatch 對象通過公共 TimeSpan Elapsed 屬性來計算完成特定任務所需的時間。我們還將計算 PDF 創建所花費的總時間。 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 實例,您可以開始和停止計時器以測量經過的時間:

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. 計時器的進階功能

Stopwatch 類別提供了除了基本時間測量之外的多項進階功能。讓我們來探討這些功能:

3.1. Restart 方法

Restart 方法是一種便捷的方式,能夠在單個操作中停止並將經過的時間重設為零。當測量多個程式碼段的執行時間而不創建新的 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. 頻率屬性

Frequency 屬性返回底層定時器每秒的計時滴答數。這個值在將經過的計時滴答轉換為其他時間單位(例如毫秒)時非常有用。

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# 中安裝 IronPDF

要在 C# 應用程式中開始使用 IronPDF,請按照以下簡單步驟操作:

  1. NuGet 套件管理器:在 Visual Studio 中打開您的 C#專案,然後導航到套件管理器主控台。執行以下命令來安裝 IronPDF:
   Install-Package IronPdf

或者,您可以使用 NuGet 套件網站 下載並安裝"IronPDF"套件。

  1. 代碼中引用:成功安裝後,將IronPDF添加到您的C#代碼中:
   using IronPdf;
   using IronPdf;
Imports IronPdf
VB   C#

現在,您已準備好在您的應用程式中利用 IronPDF 的功能。

4.2. 使用 C# 的 Stopwatch 計時建立 PDF 檔案從 URL

現在,讓我們示範如何使用 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測量所需時間。調整urlToConvert變數為所需的URL,並根據需要進一步自定義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.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >