【发布时间】:2017-06-11 11:05:09
【问题描述】:
我为 C++ 中的多线程编写了一个非常简单的示例。为什么多线程和单线程的执行时间几乎相同?
代码:
#include <iostream>
#include <thread>
#include <ctime>
using namespace std;
// function adds up all number up to given number
void task(int number)
{
int s = 0;
for(int i=0; i<number; i++){
s = s + i;
}
}
int main()
{
int n = 100000000;
////////////////////////////
// single processing //
////////////////////////////
clock_t begin = clock();
task(n);
task(n);
task(n);
task(n);
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "time single-threading: "<< elapsed_secs << " sec" << endl;
////////////////////////////
// multiprocessing //
////////////////////////////
begin = clock();
thread t1 = thread(task, n);
thread t2 = thread(task, n);
thread t3 = thread(task, n);
thread t4 = thread(task, n);
t1.join();
t2.join();
t3.join();
t4.join();
end = clock();
elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "time multi-threading: " << elapsed_secs << " sec" << endl;
}
对我来说程序的输出是
time single-threading: 0.755919 sec
time multi-threading: 0.746857 sec
我用
编译我的代码g++ cpp_tasksize.cpp -std=c++0x -pthread
我在 24-core-linux-machine 上运行
【问题讨论】:
-
不就是因为编译器对
task函数进行了微不足道的优化吗?如task等价于void task(int number) {}。 -
不,我不这么认为。我可以在
task函数的末尾添加cout << s << endl;。然后在每次执行时打印出总和,但对于多/单处理仍然是同一时间 -
在未启用优化器的情况下切勿测量时间。
-
@OliBlum
cout有一个不同的问题:AFAIK 它(在某种程度上)是线程安全的,这意味着一次只有一个线程可以刷新缓冲区。根据实现,这可能意味着其他线程被锁定。而且由于无论如何都会优化循环并且线程大部分时间都花在couting上,所以你有类似的时间。尝试改用std::this_thread::sleep_for,看看会发生什么。 -
不能保证多线程会比单线程快。如果您不受计算限制,事实上,多线程的开销很可能会使您的应用程序变慢。如果您必须同步多个线程的操作(例如,因为您正在执行诸如写入控制台之类的操作),则几乎保证多个线程不会显示出比单个线程有任何改进。
标签: c++ multithreading