跳至頁尾內容
.NET幫助

C# Stopwatch(開發者的工作原理)

在廣闊的程式語言領域中,C# 以其用於開發廣泛應用程式(從桌面到網頁和行動應用程式)的多功能性和強大性而脫穎而出。 C# 成為開發者最愛的其中一個關鍵特點是其豐富的程式庫和類別集,提供了各種程式設計挑戰的解決方案。 在這些中,Stopwatch 類別 因其在精確時間測量、設定配置和效能分析中的角色而擁有特殊的地位。

在本文中,我們將看看如何在 C# 中使用 Stopwatch 物件來找到執行特定任務所花費的時間,利用 public TimeSpan Elapsed 屬性。 此外,我們將計算使用 IronPDF for C# Developers 建立 PDF 所測量的總經過時間。

1. 什麼是 Stopwatch 類別?

Stopwatch 類別是 C# 中 System.Diagnostics 名稱空間的一部分,提供了一種簡單且有效的方法來以高精度測量經過時間。 它隨著 .NET Framework 的推出,使得開發者能更有效地追蹤程式執行時間、優化效能和剖析應用程式。

2. 初始化和基本用法

using 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 - Restart 輸出

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. 在程式碼中引用: 成功安裝後,將 IronPDF 引入到您的 C# 程式碼中:

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

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

4.2. 使用 C# Stopwatch 來計時從 URL 建立 PDF

現在,我們來演示如何使用 C# 的 Stopwatch 類別來測量從 URL 建立 PDF 所花費的時間,使用 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
$vbLabelText   $csharpLabel

此範例初始化 IronPDF,使用 HtmlToPdf 類別從指定 URL 渲染 PDF,並使用 Stopwatch 測量所花費的時間。 調整 urlToConvert 變數,使用所需的 URL,並且您可以根據需要進一步自訂 PDF 建立過程。

輸出:

C# Stopwatch (如何在開發者中運作):圖 6 - PDF 建立計時輸出

5. 結論

總而言之,C# 中的 Stopwatch 類別作為精確時間測量和效能分析的重要工具,提供了開發者優化程式碼和評估操作效率的方法。 其直觀的介面和先進的功能使其適用於各種計時需求。 此外,將 IronPDF 整合到 C# 專案中擴充了語言在 PDF 文件操作上的能力,提供了一個生成、修改和處理 PDF 的無縫解決方案。 using 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文件,如報告和發票。

如何將Stopwatch與C#中的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一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話