用 C# 計算方法的執行時間
使用 Stopwatch 類測量 .NET 中方法的執行時間 -
Stopwatch s = Stopwatch.StartNew();
現在設定一個函式並使用 ElapsedMilliseconds 屬性以毫秒為單位獲取執行時間 -
s.ElapsedMilliseconds
讓我們看看完整的程式碼 -
示例
using System;
using System.IO;
using System.Diagnostics;
public class Demo {
public static void Main(string[] args) {
Stopwatch s = Stopwatch.StartNew();
display();
for (int index = 0; index < 5; index++) {
Console.WriteLine("Time taken: " + s.ElapsedMilliseconds + "ms");
}
s.Stop();
}
public static void display() {
Console.WriteLine("Demo function!");
}
}輸出
Demo function! Time taken: 15ms Time taken: 16ms Time taken: 16ms Time taken: 16ms Time taken: 16ms
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP