跳過到頁腳內容
.NET幫助

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

在龐大的程式語言領域中,C# 脫穎而出,是一種多用途且功能強大的語言,可用於開發從桌上型電腦到網頁和行動應用程式等各式各樣的應用程式。 C# 深受開發人員喜愛的主要特點之一是其豐富的函式庫和類型,可為各種程式設計挑戰提供解決方案。 其中,Stopwatch 類別因其在精確時間測量、剖析和效能分析中的作用而佔有特殊地位。

在這篇文章中,我們將看如何使用 C# 中的 Stopwatch 物件,利用公有 TimeSpan Elapsed 屬性找出執行特定任務所需的時間。 此外,我們將計算使用 IronPDF for C# Developers 建立 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 (How It Works For Developers):圖 1 - 系統計時器輸出

3.秒表的進階功能

Stopwatch 類別除了基本的計時功能外,還提供了幾個高級功能。 讓我們來探討其中一些功能:

3.1.重新啟動方法

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 (How It Works For Developers):圖 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 (How It Works For Developers):圖 3 - 高解析度計時輸出

3.3.頻率屬性

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 (How It Works For Developers):圖 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 (How It Works For Developers):圖 5 - 輸出耗盡的 Ticks

4. Introduction to IronPDF in C#

IronPDF for .NET 是一個功能強大的 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# 秒錶為從 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 (How It Works For Developers):圖 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 文件。

如何將 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核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

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