【发布时间】:2014-11-21 09:11:28
【问题描述】:
我已使用 C++11 工具将数字运算应用程序升级为多线程程序。它在 Mac OS X 上运行良好,但不能从 Windows 上的多线程 (Visual Studio 2013) 中受益。使用以下玩具程序
#include <iostream>
#include <thread>
void t1(int& k) {
k += 1;
};
void t2(int& k) {
k += 1;
};
int main(int argc, const char *argv[])
{
int a{ 0 };
int b{ 0 };
auto start_time = std::chrono::high_resolution_clock::now();
for (int i = 0; i < 10000; ++i) {
std::thread thread1{ t1, std::ref(a) };
std::thread thread2{ t2, std::ref(b) };
thread1.join();
thread2.join();
}
auto end_time = std::chrono::high_resolution_clock::now();
auto time_stack = std::chrono::duration_cast<std::chrono::microseconds>(
end_time - start_time).count();
std::cout << "Time: " << time_stack / 10000.0 << " micro seconds" <<
std::endl;
std::cout << a << " " << b << std::endl;
return 0;
}
我发现在 Mac OS X 上启动一个线程需要 34 微秒,而在 Windows 上则需要 340 微秒。我在 Windows 方面做错了吗?是编译器问题吗?
【问题讨论】:
-
我在这里运行了您的示例,rextester.com/HMWGM22211,平均得到 400 微秒。你得到类似的结果吗?
-
算法并行不尴尬,我需要在单个 CPU 上并行化一些需要大约 500 微秒的代码。在 Mac OS X 上启动一个线程需要 30 微秒。为什么在 Windows 上也需要 300 微秒?
-
贾格纳特:谢谢你的提示。是的,我在这个网站上也得到了大约 400 微秒。这与我在机器上的 Visual Studio 2013 上得到的相同。但在同一硬件上的 Mac OS X 和 Linux 上,它的速度要快 10 倍。
-
尝试使用 boost::thread 看看 boost 的实现是否更快。
-
顺便说一句,使用 clang 运行(不确定它托管在哪个平台上)rextester.com/TRXP85153 更快。
标签: windows multithreading c++11