使用MPI时计算CPU时间

时间:2016-04-06 10:06:27

标签: c++ parallel-processing mpi cpu-time

我正在研究MPI中的并行矩阵 - 矩阵乘法器。我有计算部分工作,但我也想计算CPU时间。我陷入困境,因为看起来某些进程报告的开始和结束时间为0,对于一个应该在一秒钟内完成的任务(小矩阵),程序报告的CPU时间超过1000次(即使我知道它运行在观察下一秒钟内)。这就是我目前正在做的事情:

#include <time.h>
#include "mpi.h"
// other includes
int main()
{
    int start, end, min_start, min_end;
    if (rank == 0)
    {
        // setup stuff

        start = clock();
        MPI_Reduce(&min_start, &start, 1, MPI_INT, MPI_MIN, 0, MPI_COMM_WORLD);

        // master computation stuff

        end = clock();
        MPI_Reduce(&max_end, &end, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD);

        cout << "CPU time was " 
             << (double)(max_end - min_start) / CLOCKS_PER_SEC 
             << " seconds" << endl;
    }   
    else if (rank != 0)
    {
        // setup stuff

        start = clock();
        MPI_Reduce(&min_start, &start, 1, MPI_INT, MPI_MIN, 0, MPI_COMM_WORLD);

        // slave computation stuff

        end = clock();
        MPI_Reduce(&max_end, &end, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD);
    }
}

我不确定错误的来源是什么。当我在此调试输出中添加(在if (rank == 0)else if (rank != 0)语句之后)

MPI_Barrier(MPI_COMM_WORLD);
for (int i=0; i<size; i++)
{
    if (rank == i)
        cout << "(" << i << ") CPU time = " 
             << end << " - " << start 
             << " = " << end - start << endl;
    MPI_Barrier(MPI_COMM_WORLD);
}

我得到以下输出

CPU time was 1627.91 seconds
(1) CPU time = 0 - 0 = 0
(2) CPU time = 0 - 0 = 0
(0) CPU time = 1627938704 - 32637 = 1627906067
(3) CPU time = 10000 - 0 = 10000

1 个答案:

答案 0 :(得分:0)

首先,man 3 clock表示“clock()函数返回程序使用的处理器时间的近似值”。因此,要确定您不需要计算差异的时间。这种误解是错误的根源。您只需在密集计算后调用它,忽略setup stuff消耗的时间。

如果您不想考虑设置时间,那么您真的需要区别。因此,只需使用简单而强大的MPI_Wtime函数,该函数可以获得自过去固定时刻以来的精确秒数。

通过从最大结束时间减去最小开始时间得到的值不是通常接受的术语中的总CPU时间(即,以time效用)。那个时间是real时间。要获得确实的CPU时间,您应该总结所有处理时间,即使用时差和MPI_Reduce操作来调用MPI_SUM