两个函数之间经过的时间

sam*_*ion 19 c# algorithm time

我需要找到两个函数执行相同操作但用不同算法编写的时间.我需要找到两者中最快的

这是我的代码片段

Stopwatch sw = new Stopwatch();
sw.Start();
Console.WriteLine(sample.palindrome()); // algorithm 1
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);//tried sw.elapsed and sw.elapsedticks
sw.Reset(); //tried with and without reset
sw.Start();
Console.WriteLine(sample.isPalindrome()); //algorithm 2
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
Run Code Online (Sandbox Code Playgroud)

从技术上讲,这应该给两个算法花费的时间.这使得算法2更快.但是如果我交换两个函数的调用,它会给出不同的时间.就像我先调用algorithm2而第二次调用algorithm1一样,它表示algorithm1更快.

我不知道我做错了什么.

Ami*_*ich 21

我假设你的回文方法在这个例子中运行得非常快,因此为了获得真实的结果,你需要运行它们几次然后决定哪个更快.
像这样的东西:

int numberOfIterations = 1000; // you decide on a reasonable threshold.
sample.palindrome(); // Call this the first time and avoid measuring the JIT compile time
Stopwatch sw = new Stopwatch();
sw.Start();
for(int i = 0 ; i < numberOfIterations ; i++)
{
   sample.palindrome(); // why console write?
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds); // or sw.ElapsedMilliseconds/numberOfIterations 
Run Code Online (Sandbox Code Playgroud)

现在对第二种方法做同样的事情,你会得到更真实的结果.

  • 我同意,但仍然值得指出,因为在衡量绩效时这是一个常见的错误. (2认同)

Dev*_*ion 8

你必须做的是在编译代码的实际计算测试之前执行这两种方法JIT'd.然后尝试多次尝试.这是一个代码模型.

CIL格式的编译代码将在首次执行时进行JIT,它将被转换为机器代码.因此,首先测试它是不准确的.因此,在实际测试之前,让代码进行JIT.

sample.palindrome();
sample.isPalindrome();
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 1000; i++)
{
    sample.palindrome();
    Console.WriteLine("palindrome test #{0} result: {1}", i, sw.ElapsedMilliseconds);
}
sw.Stop();
Console.WriteLine("palindrome test Final result: {0}", sw.ElapsedMilliseconds);
sw.Restart();
for (int i = 0; i < 1000; i++)
{
    sample.isPalindrome();
    Console.WriteLine("isPalindrome test #{0} result: {1}", i, sw.ElapsedMilliseconds);
}
sw.Stop();
Console.WriteLine("isPalindrome test Final result: {0}", sw.ElapsedMilliseconds);
Run Code Online (Sandbox Code Playgroud)

阅读有关CIL和JIT的更多信息