gpt4 book ai didi

计算C中耗时

转载 作者:行者123 更新时间:2023-12-03 09:26:34 25 4
gpt4 key购买 nike

我是 C 新手,我正在使用 Linux。我被这个大学任务困住了。我需要评估程序,并且需要制作一个程序来显示执行所用的时间。这是原始程序。

/*
* Simple MPI program to sum the numbers from 1 to 1000
*
* The output of this program should look like this:
*
* $ mpirun -n 4 ./su
* node 1 of 4 starting at 251 and ending at 500
* node 2 of 4 starting at 501 and ending at 750
* node 3 of 4 starting at 751 and ending at 1000
* node 0 of 4 starting at 1 and ending at 250
* The sum from 1 to 1000 is: 500500
*
* Author: Kevan Buckley
*/

#include <stdio.h>
#include <mpi/mpi.h>

int main(int argc, char **argv) {
// Rank is which process this code is executing in.
// Rank 0 is the initial process.
int rank;
int size;
int sum = 0;
int start, end, accum, i;

// These lines must appear at the start of any
// MPI program.
MPI_Status status;
MPI_Init(&argc, &argv);

// These lines tell MPI that rank and size are values
// that we want to communicate between processes.
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);

// Only compute part of the sum.
// This splits the work over the different processes.
start = (1000*rank/size)+1;
end = 1000*(rank+1)/size;

printf("node %d of %d start: %d end: at %d\n",\
rank, size, start, end);

for(i=start; i<=end; i++){
sum = sum + i;
}

if(rank == 0) {
for(i=1; i<size; i++){
// Receive a message from another process.
MPI_Recv(&accum, 1, MPI_INT, i, 1, \
MPI_COMM_WORLD, &status);
sum = sum + accum;
}
printf("The sum from 1 to 1000 is: %d\n", sum );
}
else {
// Send data to the process at rank 0.
MPI_Send(&sum, 1, MPI_INT, 0, 1, MPI_COMM_WORLD);
}

// This code must end any MPI program.
MPI_Finalize();

return 0;
}

这是我的更新版本 - Gist 。我从我正在处理的其他代码中获取了所有时间计算。我尝试了很多东西,但仍然无法让它发挥作用。

任何帮助都会有帮助,谢谢!

最佳答案

如果我理解正确的话,你想为你的程序的一部分计时。下面是使用 MPI_Wtime 进行并行编程的示例代码。

#include <mpi.h>

double start, finish;

MPI_Init (&argc, &argv);
start=MPI_Wtime(); /*start timer*/

/*put the code you want to time here*/

finish=MPI_Wtime(); /*stop timer*/
MPI_Finalize();

printf("Parallel Elapsed time: %f seconds\n", finish-start);

关于计算C中耗时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19935447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com