我试图测量两个函数的运行时间,我在两个函数中都设置了计时器。但是如果我运行这些连续的秒返回0ms,为什么呢?
using System;
using System.Collections.Generic;
namespace TestParallelLoops
{
class Program
{
static void Main(string[] args)
{
first();
second();
}
static void first()
{
var watch = new System.Diagnostics.Stopwatch();
watch.Start();
Console.WriteLine(fibonacci(50));
watch.Stop();
Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms");
}
static void second()
{
var watch1 = new System.Diagnostics.Stopwatch();
watch1.Start();
Console.WriteLine(fibonacciRecursive(50));
watch1.Stop();
Console.WriteLine($"Execution Time: {watch1.ElapsedMilliseconds} ms");
}
static long fibonacci(int n)
{
Dictionary<int, long> last = new Dictionary<int, long>();
last[0] = 0;
last[1] = 1;
int next = 2;
while (next<=n)
{
last[next] = last[next-1] + last[next-2];
next++;
}
return last[n];
}
static long fibonacciRecursive (int n)
{
if (n == 0) return 1;
if (n == 1) return 1;
return fibonacciRecursive(n - 1) + fibonacci(n - 2);
}
}
}如果我只执行第一次,我会看到~100ms,如果我只执行第二次,我会看到~100ms,但如果我同时执行,我会看到~100ms和0ms。
非常感谢
发布于 2019-07-12 05:07:40
我认为你的100ms可能是解锁控制台所需的时间。将值保存为off并将控制台写到timed块之外,如下所示(对first()方法执行相同的操作):
static void second()
{
var watch1 = new System.Diagnostics.Stopwatch();
watch1.Start();
var a = fibonacciRecursive(50);
watch1.Stop();
Console.WriteLine(a);
Console.WriteLine($"Execution Time: {watch1.ElapsedMilliseconds} ms");
}https://stackoverflow.com/questions/56997130
复制相似问题