3 回答

TA貢獻1780條經驗 獲得超5個贊
我建議您接受一個更通用的操作,您可以將它用于更多功能。然后,您可以使用 lamda 表達式調用它。例子:
private static long MeasureDuration(Action algorithm)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
algorithm.Invoke();
watch.Stop();
return watch.ElapsedMilliseconds;
}
我使用 .Invoke() 進行鏈接,這樣更容易理解這是一個被調用的操作。
并這樣稱呼它:
bool found;
var result = MeasureDuration(() => found = BinarySearching(myArray, mySearchValue));

TA貢獻1851條經驗 獲得超5個贊
Func<bool>你可以像這樣傳遞一個參數:
public static TimeSpan Measure(Func<int[], int, bool> method, int[] arg1, int arg2)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
var result = method.Invoke(arg1, arg2);
stopwatch.Stop();
return stopwatch.Elapsed;
}
然后你可以像這樣調用它:
var timeTaken = Measure(MethodToMeasure, new [] {1, 2, 3}, 1);

TA貢獻1884條經驗 獲得超4個贊
假設您不想像基于 Action 的答案那樣丟棄算法的結果,實現它的最通用方法可能是在返回類型中使方法泛型,并將算法的輸入參數綁定到 lambda表達式,因此具有類型Func<T>. 我假設您可以使用新的 C# 7 元組語法
private static (T, long) GetResultAndDuration<T>(Func<T> algorithm)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
T result = algorithm();
watch.Stop();
return (result, watch.ElapsedMilliseconds);
}
你可以這樣稱呼它:
(var result, var duration) = GetResultAndDuration(() => MyCoolAlgorithm(42, "some param"));
- 3 回答
- 0 關注
- 140 瀏覽
添加回答
舉報