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一旦 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可使用 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 ClassOutput:

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 ClassOutput:

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 ClassOutput:

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 ClassOutput:

3.4.ElapsedTicks 屬性。
ElapsedTicks 屬性可直接存取原始的 tick 次數,而無需將其轉換為時間單位。 在執行自訂計算或處理低階時序需求時,這將大有助益。
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 ClassOutput:

4.C#中的 IronPDF 介紹。
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 Class4.1.在 C# 中安裝 IronPDF;。
要開始在您的 C# 應用程式中使用 IronPDF,請遵循以下簡單步驟:
1.NuGet套件管理員:在 Visual Studio 中開啟您的 C# 專案,並導航至套件管理員控制台。 執行下列指令安裝 IronPdf:
:ProductInstall :ProductInstall另外,您也可以使用 IronPDF NuGet 套件頁面 下載並安裝"IronPdf"套件。
2.程式碼中的參考:安裝成功後,在您的 C# 程式碼中加入對 IronPDF 的參考:
using IronPdf; using IronPdf;Imports IronPdf現在,您已準備好在您的應用程式中利用 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本範例初始化 IronPDF,使用 HtmlToPdf 類從指定的 URL 渲染 PDF,並使用 Stopwatch 測量所花的時間。 使用所需的 URL 調整 urlToConvert 變數,您可以根據應用程式的需要進一步自訂 PDF 建立流程。
Output:

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 class 為 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 Package Manager 安裝 IronPDF。在套件管理員控制台執行指令 Install-Package IronPdf 並在程式碼中包含 using IronPdf; 以存取其功能。
為何 Stopwatch 類別對 C# 的效能調整至關重要?
Stopwatch 類別對效能調整至關重要,因為它提供精確的計時功能,可協助開發人員測量和分析程式碼的執行時間。此資訊對於識別緩慢的作業和改善應用程式效能非常重要。







