用C语言,求数组长度为10000的浮点数(精确小数点右4位)计算值。要求:1对于长度为10000的数组,随机生成10000个浮点数(父进程);②创建4个子进程,分别求2500个浮点数之和; ③父进程完成10000个浮点数之和,并打印结果;④统计顺序计算的时间和多个进程采用多道程序设计完成计算的时间。
时间: 2023-04-12 12:02:05 浏览: 141
C语言程序设计-把20个随机数存入一个数组,然后输出该数组中的最小值;其中确定最小值的下标的操作在fun函数中实现
5星 · 资源好评率100%
可以使用以下代码来实现:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/wait.h>
#define ARRAY_SIZE 10000
#define CHILDREN_NUM 4
#define PRECISION 10000
int main() {
srand(time(NULL));
double array[ARRAY_SIZE];
for (int i = 0; i < ARRAY_SIZE; i++) {
array[i] = (double)rand() / RAND_MAX;
}
clock_t start, end;
double sum = 0;
start = clock();
for (int i = 0; i < ARRAY_SIZE; i++) {
sum += array[i];
}
end = clock();
printf("Sequential calculation time: %f seconds\n", (double)(end - start) / CLOCKS_PER_SEC);
start = clock();
int pipefd[CHILDREN_NUM][2];
pid_t pid[CHILDREN_NUM];
for (int i = 0; i < CHILDREN_NUM; i++) {
if (pipe(pipefd[i]) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid[i] = fork();
if (pid[i] == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid[i] == 0) {
close(pipefd[i][0]);
double partial_sum = 0;
for (int j = i * ARRAY_SIZE / CHILDREN_NUM; j < (i + 1) * ARRAY_SIZE / CHILDREN_NUM; j++) {
partial_sum += array[j];
}
write(pipefd[i][1], &partial_sum, sizeof(double));
close(pipefd[i][1]);
exit(EXIT_SUCCESS);
}
close(pipefd[i][1]);
}
for (int i = 0; i < CHILDREN_NUM; i++) {
double partial_sum;
read(pipefd[i][0], &partial_sum, sizeof(double));
sum += partial_sum;
close(pipefd[i][0]);
waitpid(pid[i], NULL, 0);
}
end = clock();
printf("Parallel calculation time: %f seconds\n", (double)(end - start) / CLOCKS_PER_SEC);
printf("Sum: %.*f\n", PRECISION, sum);
return 0;
}
阅读全文