C# lock和Interlocked性能测试

 

 

 

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace 测试interlock
{
    class Program
    {
        private static object lockObj = new object();
 
        private static int Count = 0;
 
        static void Main(string[] args)
        {
            int threadCount = 10;
            for (int k = 0; k < 10; k++)
            {
                Count = 0;
                var watch = new Stopwatch();
                watch.Start();
                var tasks = new List<Task>();
                for (int i = 0; i < threadCount; i++)
                {
                    var task = Task.Factory.StartNew(
                        () =>
                        {
                            for (int j = 0; j < 10000000; j++)
                            {
                                OnlyLockTest();
                            }
                        });
                    tasks.Add(task);
                }
 
                Task.WaitAll(tasks.ToArray());
                watch.Stop();
                Console.WriteLine(k + 1 + " 线程数:" + threadCount + ", Lock耗时:" + watch.ElapsedTicks + ",计算结果: " + Count);
 
                Count = 0;
                watch = new Stopwatch();
                watch.Start();
                var tasks1 = new List<Task>();
                for (int i = 0; i < threadCount; i++)
                {
                    var task = Task.Factory.StartNew(
                        () =>
                        {
                            for (int j = 0; j < 10000000; j++)
                            {
                                InterlockedTest();
                            }
                        });
                    tasks1.Add(task);
                }
 
                Task.WaitAll(tasks1.ToArray());
                watch.Stop();
                Console.WriteLine(k + 1 + " 线程数:" + threadCount + ", Interlocked耗时:" + watch.ElapsedTicks + ",计算结果: " + Count);
            }
 
            Console.ReadKey();
        }
 
        private static void OnlyLockTest()
        {
            lock (lockObj)
            {
                Count++;
            }
        }
 
        private static void InterlockedTest()
        {
            Interlocked.Increment(ref Count);
        }
    }
}

 

原文 https://blog.csdn.net/sinat_31608641/article/details/108033922

posted @ 2021-08-07 23:06  qingjiawen  阅读(256)  评论(0编辑  收藏  举报