導航:首頁 > 操作系統 > 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數字運算相關的資料

熱點內容
為什麼要編譯源代碼 瀏覽:819
輸入法freetype交叉編譯 瀏覽:437
電阻單片機代號 瀏覽:469
來畫app怎麼添加對話框 瀏覽:318
python序列化分布式 瀏覽:107
域名伺服器是什麼形式 瀏覽:681
rsa加密解密速度快 瀏覽:924
mac電腦如何單片機開發 瀏覽:547
紀念日app怎麼用小插件 瀏覽:331
如何更改安卓手機所在地區 瀏覽:217
程序員負債120萬 瀏覽:80
階層pdf 瀏覽:380
linuxgit安裝配置 瀏覽:319
用源碼搭建app要改什麼 瀏覽:42
密碼學教程pdf 瀏覽:3
亞馬遜做的加密貨幣 瀏覽:81
怎麼搭建雲播伺服器 瀏覽:867
網站客服機器人源碼 瀏覽:317
2021程序員的出路 瀏覽:547
發行與承銷pdf 瀏覽:945