首页 > 解决方案 > ConcurrentStack 性能 C++ VS Boost VS C#

问题描述

我一直试图在性能方面击败 C# 的 ConcurrentStack 实现,包括 Boost 无锁堆栈在内的几种不同实现,甚至无法接近。

Boost 下面的测试代码以 ~4.6s 的速度进入,我自己在 x64 上使用 DCAS (InterlockedCompareExchange128) 的最佳性能代码在 ~3.7s,C# 在 ~2.3s 的时间内破坏了它们。我的编译器是 MSVC,完全优化。

#include "boost/lockfree/stack.hpp" void TestPerformanceConcurrentStackBOOST() {
System::Diagnostics::Stopwatch sw = new System::Diagnostics::Stopwatch();
sw.Start();
int numThreads = 1;
boost::lockfree::stack<int> stack(128);

for (int t = 0; t < numThreads; t++) {
    for (int i = 0; i < 1000000; i++) {
        for (int q = 0; q < 100; q++) {
            stack.push(q);
        }
        for (int j = 0; j < 100; j++) {
            int res;
            stack.pop(res);
        }
    }
}

sw.Stop();
Console::WriteLine((long)sw.ElapsedMilliseconds); }

C# 测试代码:

        public static void TestPerformanceConcurrentStack() {
        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        sw.Start();
        int numThreads = 1;
        System.Collections.Concurrent.ConcurrentStack<int> stack = new System.Collections.Concurrent.ConcurrentStack<int>();
        System.Collections.Generic.List<System.Threading.ManualResetEvent> lstthreads = new System.Collections.Generic.List<System.Threading.ManualResetEvent>();


        for (int t = 0; t < numThreads; t++) {
            System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false);
            System.Threading.ThreadPool.QueueUserWorkItem((a) => {
                for (int i = 0; i < 1000000; i++) {
                    for (int q = 0; q < 100; q++) {
                        stack.Push(q);
                    }
                    for (int j = 0; j < 100; j++) {
                        int res;
                        stack.TryPop(out (res));
                    }
                }
                mre.Set();
            });
            lstthreads.Add(mre);
        }
        for (int t = 0; t < numThreads; t++) {
            lstthreads[t].WaitOne();
        }

        sw.Stop();
        Console.WriteLine((long)sw.ElapsedMilliseconds);
    }

我有理由确定这不仅仅是 C# 垃圾收集的 bc,因为我还使用自定义 GC 测试了 C++ 版本,但没有运气。我检查了 C# 代码,它非常简单,没有什么特别之处。性能分析显示 Boost 版本在 pop 方法中花费了大约 60% 的时间,类似于我的 DCAS 实现。

是否有人拥有比 C# 更快的 C++ 并发堆栈,或者您对我接下来可以尝试什么以使其更快有什么建议吗?

任何帮助深表感谢。谢谢!

标签: c#c++boostconcurrencystack

解决方案


推荐阅读