我正在編寫一些代碼來生成過程圖。 某些步驟比其他步驟耗時更長,我正在對構建的每個部分進行計時,以查看瓶頸的位置,並讓用戶知道程序沒有停頓。包裝時間通用函數
目前,我有很多的代碼看起來像這樣:
Console.Write("Creating tiles");
var watch = System.Diagnostics.Stopwatch.StartNew();
CreateTiles(); //key mapgen function
watch.Stop();
Console.WriteLine("... finished in: {0} s", watch.ElapsedMilliseconds/1000d);
Console.Write("Calculating tile elevations");
var watch = System.Diagnostics.Stopwatch.StartNew();
CalculateTileElevations(); //key mapgen function
watch.Stop();
Console.WriteLine("... finished in: {0} s", watch.ElapsedMilliseconds/1000d);
//etc
我的問題是,是否有重構這個更看起來像下面的方法:
ExecuteTimedFunction(CreateTiles(), "Creating tiles");
ExecuteTimedFunction(CalculateTileElevations(), "Calculating tile elevations");
void ExecuteTimedFunction(Func genericFunction, String logMsg)
{
Console.Write(logMsg);
var watch = System.Diagnostics.Stopwatch.StartNew();
genericFunction();
watch.Stop();
Console.WriteLine("... finished in: {0} s", watch.ElapsedMilliseconds/1000d);
}
注意:所有函數的返回類型是void
,因爲它們都操縱瓦片的主列表,但並非所有函數都具有相同數量的輸入參數(儘管大多數參數具有0個參數,因此對於該情況的解決方案會仍然有用)
如果將'genericFunction'的類型更改爲'Action',它應該ķ。然後你可以把它叫做ExecuteTimedFunction(CreateTiles,「Creating tiles」);' – Lee