首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当有两个监视实例时,StopWatch返回0ms

当有两个监视实例时,StopWatch返回0ms
EN

Stack Overflow用户
提问于 2019-07-12 04:51:28
回答 1查看 140关注 0票数 1

我试图测量两个函数的运行时间,我在两个函数中都设置了计时器。但是如果我运行这些连续的秒返回0ms,为什么呢?

代码语言:javascript
复制
    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。

非常感谢

EN

回答 1

Stack Overflow用户

发布于 2019-07-12 05:07:40

我认为你的100ms可能是解锁控制台所需的时间。将值保存为off并将控制台写到timed块之外,如下所示(对first()方法执行相同的操作):

代码语言:javascript
复制
    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");
    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56997130

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档