导航:首页 > 操作系统 > linux数字运算

linux数字运算

发布时间:2023-08-10 03:24:47

linux求数组长度为10000的浮点数(精确小数点右4位)计算值

既然题主没有说要求用什么语言,那我就用c++11实现了。

#include<iostream>

#include<random>

#include<thread>

#include<chrono>

#include<algorithm>

#include<iomanip>


usingnamespacestd;


constintsize=10000;

floattable[size];


intmain(){

random_deviceengine;

uniform_real_distribution<float>dist(0,1);

floatsum;


for(auto&i:table){

i=dist(engine);

}


autot_start=chrono::system_clock::now();

sum=accumulate(table,table+size,0.0);

autot_end=chrono::system_clock::now();

autoration=std::chrono::ration_cast<std::chrono::microseconds>(t_end-t_start).count();

cout<<"sumofthemainthread:"<<fixed<<setprecision(4)<<sum<<endl;

cout<<"timeelapsed:"<<ration<<"microseconds"<<endl;


floatsum_child[4];

autofun=[&](intindex){

sum_child[index]=accumulate(table+index*size/4,table+(index+1)*size/4,0.0);

};


t_start=chrono::system_clock::now();

threadthrd_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();

ration=std::chrono::ration_cast<std::chrono::microseconds>(t_end-t_start).count();

cout<<"sumofchildthreads:"<<fixed<<setprecision(4)<<sum<<endl;

cout<<"timeelapsed:"<<ration<<"microseconds"<<endl;


return0;

}


编译

g++-std=c++11test.cc-lpthread-otest

运行:

./test

结果:

sumofthemainthread:4976.8721

timeelapsed:0ms

sumofchildthreads:4976.8721

timeelapsed:0ms


由于随机性每次加和的数值不同,但是精确到毫秒时,时间测出来妥妥的都是零。就是数据量太小,实际运行时间在微秒量级,当然看不出来。

精度改为微秒以后:

sumofthemainthread:4957.9878

timeelapsed:113microseconds

sumofchildthreads:4957.9878

timeelapsed:560microseconds

多线程反而比单线程慢,因为启动线程本身也需要时间。

数据量再增大1000倍:

sumofthemainthread:4999892.0000

timeelapsed:25313microseconds

sumofchildthreads:4999892.0000

timeelapsed:8986microseconds

这回看着正常多了吧

㈡ linux命令 数值计算 为什么要双括号

(命令) ------> 单个括号的意思是执行括号里面的命令 ((算式)) -------> 双括号的意思是计算里面的算式. 比如 files=$(ls)sum=$((5+2)) shell本身没有计算小数的功能. 你可以用bc命令, 比如 sum=$(echo "2.2+3.3"|bc)

阅读全文

与linux数字运算相关的资料

热点内容
单片机驱动电机原理 浏览:905
app扫哈罗单车怎么操作 浏览:509
电脑版吃鸡为什么登录服务器忙 浏览:982
linux查端口命令 浏览:489
linuxhttp客户端 浏览:820
linux下运行jar包 浏览:435
彩虹弹弹解压球视频 浏览:83
pdf怎样转换成word格式 浏览:673
怎么查找解压文件在哪里 浏览:852
德语小说pdf 浏览:125
陕西联通dns服务器地址 浏览:939
js表格即时编译 浏览:304
51单片机串口拓展 浏览:307
重装系统后加密图片损坏 浏览:465
电脑怎么放大缩小app窗口 浏览:526
教育十APP学校怎么更改 浏览:823
空调外机压缩机热保护 浏览:756
winlinux双系统卸载 浏览:241
如何对安卓应用反编译 浏览:412
鲲鹏pc服务器是什么 浏览:575