首页 > 解决方案 > 将时间执行计算为单独的类,其中函数是可变的

问题描述

设如下二分查找函数:

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# 方面不起作用,你能帮我修改它或提出你自己的尝试吗?最有趣的是为所有算法找到这样的结构,而不管它产生的变量类型如何。

标签: c#algorithmtime-complexity

解决方案


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);

推荐阅读