将时间执行计算为单独的类,其中函数是可变的

设如下二分查找函数:


public static bool BinarySearching(int[] array, int searchValue)

{

    Array.Sort(array);

    double p = 0;

    double q = 0;

    int r = array.Length - 1;


    while (p <= r)

    {

        q = Math.Floor((p + r) / 2);


        if (array[(int)q] == searchValue)

        {

            return true;

        }


        else if (array[(int)q] != searchValue && array[(int)q] > searchValue)

        {

            r = (int)(q - 1);

        }


        else if (array[(int)q] != searchValue && array[(int)q] < searchValue)

        {

            p = (int)(q + 1);

        }

    }


    return false;

}

}


如果我们想测量它的执行时间,我们会做类似的事情


var watch = System.Diagnostics.Stopwatch.StartNew();

BinarySearching(int[] array, int searchValue);

watch.Stop();

var elapsedMs = watch.ElapsedMilliseconds;

但是,通过单独的函数进行测量是否有更漂亮的方法,使得变量是计算函数本身?例如,在伪代码中是


public static string ComplexityCounter(bool algorithm(int[] array, int searchValue))

{

    var watch = System.Diagnostics.Stopwatch.StartNew();

    algorithm(int[] array, int searchValue);

    watch.Stop();

    var elapsedMs = watch.ElapsedMilliseconds;

    string result = elapsedMs.ToString();

    return result;

}

而且,确定它在 C# 方面不起作用,你能帮我修改它或提出你自己的尝试吗?最有趣的是为所有算法找到这样的结构,而不管它产生的变量类型如何。


慕莱坞森
浏览 115回答 3
3回答

翻阅古今

我建议您接受一个更通用的操作,您可以将它用于更多功能。然后,您可以使用 lamda 表达式调用它。例子:&nbsp; &nbsp; private static long MeasureDuration(Action algorithm)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var watch = System.Diagnostics.Stopwatch.StartNew();&nbsp; &nbsp; &nbsp; &nbsp; algorithm.Invoke();&nbsp; &nbsp; &nbsp; &nbsp; watch.Stop();&nbsp; &nbsp; &nbsp; &nbsp; return watch.ElapsedMilliseconds;&nbsp; &nbsp; }我使用 .Invoke() 进行链接,这样更容易理解这是一个被调用的操作。并这样称呼它:&nbsp; bool found;&nbsp; var result = MeasureDuration(() => found = BinarySearching(myArray, mySearchValue));

江户川乱折腾

Func<bool>你可以像这样传递一个参数:public static TimeSpan Measure(Func<int[], int, bool> method, int[] arg1, int arg2){&nbsp; &nbsp; var stopwatch = new Stopwatch();&nbsp; &nbsp; stopwatch.Start();&nbsp; &nbsp; var result = method.Invoke(arg1, arg2);&nbsp; &nbsp; stopwatch.Stop();&nbsp; &nbsp; return stopwatch.Elapsed;}然后你可以像这样调用它:var timeTaken = Measure(MethodToMeasure, new [] {1, 2, 3}, 1);

慕村9548890

假设您不想像基于 Action 的答案那样丢弃算法的结果,实现它的最通用方法可能是在返回类型中使方法泛型,并将算法的输入参数绑定到 lambda表达式,因此具有类型Func<T>. 我假设您可以使用新的 C# 7 元组语法private static (T, long) GetResultAndDuration<T>(Func<T> algorithm){&nbsp; &nbsp;var watch = System.Diagnostics.Stopwatch.StartNew();&nbsp; &nbsp;T result = algorithm();&nbsp; &nbsp;watch.Stop();&nbsp; &nbsp;return (result, watch.ElapsedMilliseconds);}你可以这样称呼它:(var result, var duration) = GetResultAndDuration(() => MyCoolAlgorithm(42, "some param"));
打开App,查看更多内容
随时随地看视频慕课网APP