.NET幫助 C# Stopwatch(開發者的工作原理) Curtis Chau 更新日期:6月 22, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 在廣泛的程式語言中,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 输出: 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 输出: 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 输出: 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 输出: 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 输出: 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) { // 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. 在 C# 中安裝 IronPDF 要在您的 C# 應用中開始使用 IronPDF,請按照以下簡單步驟操作: NuGet 套件管理器:在 Visual Studio 中打開您的 C# 專案並導航至套件管理器控制台。 執行以下命令來安裝 IronPDF: Install-Package IronPdf 或者,您可以使用 IronPDF NuGet 套件頁面 下載並安裝 "IronPdf" 套件。 在代碼中引用:成功安裝後,在您的 C# 代碼中引用 IronPDF: using IronPdf; using IronPdf; Imports IronPdf $vbLabelText $csharpLabel 現在,您已經準備好在您的應用中利用 IronPDF 的功能。 4.2. 使用 C# Stopwatch 計時從 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 測量所需的時間。 根據需要調整 urlToConvert 變數,您可以進一步自定義 PDF 創建過程以滿足您的應用需求。 输出: 5. 結論 總結來說,C# 中的 Stopwatch 類作為準確時間測量和性能分析的關鍵工具,為開發人員提供了優化代碼和評估運行效率的手段。 其直觀的界面和高級功能使其在各種類型的計時要求中具有多功能性。 此外,在 C# 專案中集成 IronPDF 擴展了語言在 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 類別對於性能調優至關重要,因為它提供精確的計時能力,有助於開發者測量和分析程式碼執行時間。這些信息對於識別緩慢操作和提高應用程式性能至關重要。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 Jquery Datatable(開發者的工作原理)Swashbuckle ASP .NET Core(開發...