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

Linux求数组长度为10000的浮点数(精确小数点右4位)计算值,第1张

既然题主没有说要求用什么语言,那我就用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

这回看着正常多了吧

基本数据类型可以指定int的长度:类似的,还有uint32_t和uint64_t其它数据类型1,size_t:跟机器字长一样;2,off_t:32位机器下默认是32位长,这时无法对大于4G的文件偏移 *** 作,这时off_t = __off_t;如果想进行大于4G的文件偏移 *** 作,可以在程序中加入头文件之前定义这时off_t = __off64_t,具体定义在unistd.h中;对于64位机,默认就是64位长。#define _FILE_OFFSET_BITS 643,ino_t:跟机器字长一样。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/8625930.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-19
下一篇 2023-04-19

发表评论

登录后才能评论

评论列表(0条)

保存