既然题主没有说要求用什么语言,那我就用c++11实现了。
#include <iostream>
#include <random>
#include <thread>
#include <chrono>
#include <algorithm>
#include <iomanip>
using namespace std
const int size = 10000
float table[size]
int main(){
random_device engine
uniform_real_distribution<float> dist(0, 1)
float sum
for(auto& i: table){
i = dist(engine)
}
auto t_start = chrono::system_clock::now()
sum = accumulate(table, table + size, 0.0)
auto t_end = chrono::system_clock::now()
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(t_end - t_start).count()
cout << "sum of the main thread: " << fixed << setprecision(4) << sum << endl
cout << "time elapsed: " << duration << " micro seconds" << endl
float sum_child[4]
auto fun = [&](int index){
sum_child[index] = accumulate(table + index * size / 4, table + (index + 1) * size / 4, 0.0)
}
t_start = chrono::system_clock::now()
thread thrd_table[4] = {
thread(fun, 0), thread(fun, 1), thread(fun, 2), thread(fun, 3)
}
for(auto& thrd: thrd_table){
thrd.join()
}
sum = 0
sum = accumulate(sum_child, sum_child + 4, 0.0)
t_end = chrono::system_clock::now()
duration = std::chrono::duration_cast<std::chrono::microseconds>(t_end - t_start).count()
cout << "sum of child threads: " << fixed << setprecision(4) << sum << endl
cout << "time elapsed: " << duration << " micro seconds" << endl
return 0
}
编译:
g++ -std=c++11 test.cc -lpthread -o test
运行:
./test
结果:
sum of the main thread: 4976.8721
time elapsed: 0 ms
sum of child threads: 4976.8721
time elapsed: 0 ms
由于随机性每次加和的数值不同,但是精确到毫秒时,时间测出来妥妥的都是零。就是数据量太小,实际运行时间在微秒量级,当然看不出来。
精度改为微秒以后:
sum of the main thread: 4957.9878
time elapsed: 113 micro seconds
sum of child threads: 4957.9878
time elapsed: 560 micro seconds
多线程反而比单线程慢,因为启动线程本身也需要时间。
数据量再增大1000倍:
sum of the main thread: 4999892.0000
time elapsed: 25313 micro seconds
sum of child threads: 4999892.0000
time elapsed: 8986 micro seconds
这回看着正常多了吧
x=0.02while [ $x lt 0.06 ]
do
echo $x
x=`expr $x + 0.02`
done
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)