C ++ 11线程异步VS性能(VS2013) [英] C++11 thread vs async performance (VS2013)

查看:577
本文介绍了C ++ 11线程异步VS性能(VS2013)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我失去了一些东西...

I feel like I'm missing something here...

我稍微改变了一些code从使用的std ::线程的std ::异步更改并注意到大幅度的性能提升。我写了一个简单的测试,我认为应该运行几乎相同使用的std ::线程,因为它不使用的std ::异步

I slightly altered some code to change from using std::thread to std::async and noticed a substantial performance increase. I wrote up a simple test which I assume should run nearly identically using std::thread as it does using std::async.

std::atomic<int> someCount = 0;
const int THREADS = 200;
std::vector<std::thread> threadVec(THREADS);
std::vector<std::future<void>> futureVec(THREADS);
auto lam = [&]()
{
    for (int i = 0; i < 100; ++i)
        someCount++;
};

for (int i = 0; i < THREADS; ++i)
    threadVec[i] = std::thread(lam);
for (int i = 0; i < THREADS; ++i)
    threadVec[i].join();

for (int i = 0; i < THREADS; ++i)
    futureVec[i] = std::async(std::launch::async, lam);
for (int i = 0; i < THREADS; ++i)
    futureVec[i].get();

我也没太深入的分析,但有些preliminary结果使它看起来的std ::异步 code各地跑快10倍!结果与优化略有不同了,我也试着开关的执行顺序。

I didn't get too deep into analysis, but some preliminary results made it seem that std::async code ran around 10X faster! Results varied slightly with optimizations off, I also tried switching the execution order.

这是一些Visual Studio的编译器的问题?还是有我俯瞰这将占性能差别一些更深层次的实现问题?我认为,的std ::异步大约是一个包装的的std ::线程电话?

Is this some Visual Studio compiler issue? Or is there some deeper implementation issue I'm overlooking that would account for this performance difference? I thought that std::async was a wrapper around the std::thread calls?

另外考虑到这些差异,我想知道这将是在这里获得最佳性能的方法是什么? (还有比的std ::螺纹和std ::异步其中创建线程更多)

Also considering these differences, I'm wondering what would be the way to get the best performance here? (There are more than std::thread and std::async which create threads)

样,如果我想超脱线程是什么? (性病::异步不能做到这一点,据我所知)

What about if I wanted detached threads? (std::async can't do that as far as I'm aware)

推荐答案

当你使用异​​步没有创建新的线程,而不是你重用线程池的可用的。创建和销毁线程是一个非常昂贵的操作,需要在Windows操作系统中约200 000的CP​​U周期。最重要的是,记得有一个线程数超过CPU内核的数量大得多意味着操作系统需要花更多的时间来创建他们,安排他们使用每个内核的可用CPU时间。

When you're using async you are not creating new threads, instead you reuse the ones available in a thread pool. Creating and destroying threads is a very expensive operation that requires about 200 000 CPU cycles in Windows OS. On top of that, remember that having a number of threads much bigger than the number of CPU cores means that the operating system needs to spend more time creating them and scheduling them to use the available CPU time in each of the cores.

这篇关于C ++ 11线程异步VS性能(VS2013)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆