包装时间通用功能

ms8*_*813 0 c# time wrapper

我正在编写一些代码来生成程序映射.有些步骤比其他步骤花费的时间长得多,我正在计算构建的每个部分以查看瓶颈的位置,并让用户知道程序没有停滞在它们上面.

目前我有很多看起来像这样的代码:

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
Run Code Online (Sandbox Code Playgroud)

我的问题是,有没有办法重构这个看起来像下面这样的东西:

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);
}
Run Code Online (Sandbox Code Playgroud)

警告:所有函数的返回类型都是void因为它们都操作了一个主列表的tile,但并非所有函数都具有相同数量的输入参数(尽管大多数都有0个参数,因此该案例的解决方案仍然是有用)

Sco*_*ham 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);
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过以下任一方式调用它:

ExecuteTimedFunction(MyFunctionWithNoParams, "MyFunc");
ExecuteTimedFunction(() => MyFuncWithParams(p1, p2), "MyFunc2");
Run Code Online (Sandbox Code Playgroud)