没有计算密集型C#程序的好处?

时间:2012-01-06 14:54:02

标签: c# multithreading visual-studio-2010

我试图看到以下两个程序之间的性能差异(期待)。但我发现没有区别。这是正常的吗?我在Windows Core 2 Duo M / C上运行 Visual Studio 2010 Express Edition

计划1(平均超过100次运行:824.11 ms):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;


namespace MultiThreading
{
    class Program
    {
        public static Stopwatch stopwatch;
        static void Main(string[] args)
        {
            stopwatch = new Stopwatch();
            stopwatch.Start();
            //Thread t = new Thread(WriteY);
            //t.Start();
            for (int i = 0; i < 10000; i++)
            {
                Console.Write("x{0} ", i);
            }

            WriteY();

            Console.WriteLine("Time taken in milliseconds: {0}", stopwatch.ElapsedMilliseconds);
            Console.ReadLine();
        }

        static void WriteY()
        {
            for (int i = 0; i < 10000; i++)
            {
                Console.Write("y{0} ", i);
            }
            //Console.WriteLine("Time taken in milliseconds: {0}", stopwatch.ElapsedMilliseconds);
            //Console.ReadLine();
        }

计划2(平均超过100次运行:828.11 ms):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;


namespace MultiThreading
{
    class Program
    {
        public static Stopwatch stopwatch;
        static void Main(string[] args)
        {
            stopwatch = new Stopwatch();
            stopwatch.Start();
            Thread t = new Thread(WriteY);
            t.Start();
            for (int i = 0; i < 10000; i++)
            {
                Console.Write("x{0} ", i);
            }

            //WriteY();

            Console.WriteLine("Time taken in milliseconds: {0}", stopwatch.ElapsedMilliseconds);
            Console.ReadLine();
        }

        static void WriteY()
        {
            for (int i = 0; i < 10000; i++)
            {
                Console.Write("y{0} ", i);
            }
            //Console.WriteLine("Time taken in milliseconds: {0}", stopwatch.ElapsedMilliseconds);
            //Console.ReadLine();
        }
    }
}

2 个答案:

答案 0 :(得分:8)

我的猜测是两者都受Console.Write的速度限制,这可能需要锁定资源(屏幕),以便一次只能访问一个线程。

答案 1 :(得分:4)

问题是您的应用程序是IO绑定的,因为您始终使用Console.WriteLine。如果你做了一些没有使用IO的东西,你会看到一个提升。

正如其他答案[{1}}中提到的那样确实同步:Calling Console.WriteLine from multiple threads