在 C 中运行并发进程并测量运行时间

问题描述 投票:0回答:1

我正在用 C 创建一个程序,从文件中加载一个矩阵,将其分为 N 个段以提供给 N 个进程。

每个进程都应该计算矩阵该段中的每个 0 元素。

我应该测量完成整个程序所需的时间。因此,理论上,如果我添加更多进程,则花费的时间应该更少,呈反比意义。

为此,我测量了每个进程的时间,如下所示:

for (int i = 0; i < num_processes; ++i)
  {
    pid_t pid = fork();

    if (pid == -1)
    {
      perror("Fork failed");
      exit(EXIT_FAILURE);
    }

    if (pid == 0)
    {
      // Child process

      // Calculate the start and end rows for this process
      int start_row = i * segment_rows + (i < remaining_rows ? i : remaining_rows);
      int end_row = start_row + segment_rows + (i < remaining_rows ? 1 : 0);

      // Perform counting in the segment
      start = clock();
      long count = countZeros(matrix + start_row * columns, end_row - start_row, columns);
      end = clock();

      // Print the count and time taken by this process
      printf("Process %d Count: %ld Time: %f seconds\n", i, count, ((double)(end - start)) / CLOCKS_PER_SEC);

      exit(EXIT_SUCCESS);
    }
  }

例如,当我使用 1000 x 2000 矩阵运行它时,如果我继续添加进程,每个进程的时间确实会减少(我设置的限制是可用的 CPU 核心数量)。

问题是,当我这样测量整个程序时间时:

// Wait for all child processes to finish
  start = clock();
  for (int i = 0; i < num_processes; ++i)
  {
    wait(NULL);
  }
  end = clock();
// Print the total time taken by all processes
  printf("Total time: %f seconds\n", ((double)(end - start)) / CLOCKS_PER_SEC);

现在的时间不仅增加了,甚至与所有进程的时间没有关系。

那么最后的问题是,是否应该用其他方式来衡量总体时间,或者这个问题与程序中所做的并发管理有关?

以下是一些显示所描述问题的屏幕截图:

这是包含完整代码的存储库:https://github.com/NicolasMonta1807/matrix-concurrency

如果您对更多感兴趣,这应该应用于此处构建的稀疏矩阵验证器:https://github.com/NicolasMonta1807/sparse-matrix-validator。总的来说,它可以正常工作并且完成其工作,但唯一的问题是这篇文章中所述。

c concurrency process sparse-matrix
1个回答
0
投票

所以,最后还是用

clock()
来衡量。我用
clock_gettime()
替换了它,正如 Weather Vane 在他们的评论中建议的那样,它正在按预期工作。

/**
     * ---------- TIMER ----------
     */
    struct timespec begin, end;
    clock_gettime(CLOCK_REALTIME, &begin);

    int total = 0;

    for (int i = 0; i < num_processes; ++i)
    {
      wait(NULL);
    }

    clock_gettime(CLOCK_REALTIME, &end);
    double time_spent = (end.tv_sec - begin.tv_sec) +
                        (end.tv_nsec - begin.tv_nsec) / BILLION;
    printf("Terminado en %f\n", total, time_spent);

我真的很感谢你的帮助。

© www.soinside.com 2019 - 2024. All rights reserved.