我正在编写一些代码来生成程序映射。 有些步骤比其他步骤花费的时间长得多,我可以对构建的每个部分进行计时,以查看瓶颈的位置,并让用户知道程序没有停滞在它们上面。
目前我有很多代码如下:
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
,因为它们都操作了一个主列表的tile,但并非所有函数都具有相同数量的输入参数(尽管大多数函数都有0个参数所以针对该案例的解决方案仍然有用)
答案 0 :(得分:8)
您的ExecuteTimedFunction
方法看起来像这样:
public void ExecuteTimedFunction(Action action, string name)
{
Console.Write(name);
var watch = Stopwatch.StartNew();
action();
watch.Stop();
Console.WriteLine("... finished in: {0} s", watch.ElapsedMilliseconds/1000d);
}
然后您可以通过以下任一方式调用它:
ExecuteTimedFunction(MyFunctionWithNoParams, "MyFunc");
ExecuteTimedFunction(() => MyFuncWithParams(p1, p2), "MyFunc2");
答案 1 :(得分:0)
您还可以通过将其更改为以下内容来访问要调用的方法详细信息:
Console.WriteLine($"{action.Method.Name} finished in: {watch.ElapsedMilliseconds / 1000d} s");