使用MPI时计算CPU时间

Calculating CPU Time when using MPI

本文关键字:CPU 时间 计算 MPI 使用      更新时间:2023-10-16

我正在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

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

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

从最大结束时间减去最小开始时间得到的值不是公认的总CPU时间(即time实用程序)。那个时间是real时间。要获得真正的CPU时间,您应该将所有处理时间相加,即调用具有时间差的MPI_ReduceMPI_SUM操作。