c# - 将时间执行计算为单独的类,其中函数是可变的
问题描述
设如下二分查找函数:
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# 方面不起作用,你能帮我修改它或提出你自己的尝试吗?最有趣的是为所有算法找到这样的结构,而不管它产生的变量类型如何。
解决方案
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);
推荐阅读
- macos - 无法在 VS2017 7.6 中打开 Specflow 功能文件(适用于 MAC)
- python - Wagtail API - 如何公开片段
- python - 通过 Halley 方法使用 tensorflow 求 4 次多项式的根
- microsoft-teams - Microsoft Teams 需要什么条件才能创建传出 Webhook?
- python - django 默认日期格式为 %d-%m-%Y
- jira - 如何获取最近两周打开的已完成项目的状态
- java - 如何运行使用测试资源而不是主要资源的 Java 应用程序?
- apache-tika - Tika:检测到错误的 mime 类型
- batch-file - 使用批处理脚本更新键的值
- function - 如何转换函数类型?