目录
- 欧拉-黎曼函数的K阶近似(OpenMP实现和MPI实现)
- 问题描述
- OpenMP代码实现
- MPI代码实现
- 注意事项
- 运行
- 参考资料
欧拉-黎曼函数的K阶近似(OpenMP实现和MPI实现)
问题描述
OpenMP代码实现
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
#include<time.h>
#include <windows.h> //window环境下调用Sleep()函数包含此头文件
double zeta_approximation(int s, int k)
{
double result = 0.0;
#pragma omp parallel for reduction(+:result)
for (int i = 1; i <= k; i++) {
for (int j = 1; j <= k; j++)
{
//result += 1.0 / (pow(n, k) * pow(k, n));
result += pow(-1, i+1) / pow(i+j, s);
}
}
return result * pow(2, s);
}
int main()
{
int s = 20;
int k = 3000;
clock_t start = 0;
clock_t end = 0;
double approximation = 0.0;
start = clock();
for (int i = 1; i <= k; i++) {
for (int j = 1; j <= k; j++)
{
//result += 1.0 / (pow(n, k) * pow(k, n));
approximation += pow(-1, i + 1) / pow(i + j, s);
}
}
approximation = approximation * pow(2, s);
end = clock();
printf("zeta(%d, %d) ≈ %f\n", s, k, approximation);
printf("总的cpU时间 = %f\n", (end - start) / (double)CLOCKS_PER_SEC);
omp_set_num_threads(4); // 设置线程数量
approximation = 0.0;
start = 0;
end = 0;
start = clock();
approximation = zeta_approximation(s, k);
end = clock();
printf("Zetaop(%d, %d) ≈ %f\n", s, k, approximation);
printf("总的CPU时间 = %f\n", (end - start) / (double)CLOCKS_PER_SEC);
return 0;
}
MPI代码实现
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <mpi.h>
double zeta_approximation(int s, int k, int rank, int num_procs)
{
double result = 0.0;
int start = rank * (k / num_procs) + 1;
int end = (rank + 1) * (k / num_procs);
if (rank == num_procs - 1) {
end = k;
}
for (int i = start; i <= end; i++) {
for (int j = 1; j <= k; j++) {
result += pow(-1, i + 1) / pow(i + j, s);
}
}
return result;
}
int main(int argc, char** argv)
{
int s = 20;
int k = 800;
double approximation = 0.0;
double total_approximation = 0.0;
int rank, num_procs;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
double start_time = MPI_Wtime();
approximation = zeta_approximation(s, k, rank, num_procs);
MPI_Reduce(&approximation, &total_approximation, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
double end_time = MPI_Wtime();
if (rank == 0) {
printf("Zetaop(%d, %d) ≈ %f\n", s, k, total_approximation * pow(2, s));
printf("总的CPU时间 = %f\n", end_time - start_time);
}
MPI_Finalize();
return 0;
}
注意事项
关于运行多线程,因为vs2019中只能显示一个线程的程序,所以我们要到cmd中实现多线程程序。
保存一下你的代码,到项目中找到exe程序,如下图。(一定是项目目录x64下的Debug中)
在路径栏中输入cmd打开dos窗口,输入下面这句话
mpiexec -n 8 demo.exe
8代表8个线程,后面是我的文件名,需要替换为你自己的文件名,回车运行即可。
运行
win10 + vs2019