c++ - 为什么我不能通过在 C++11 中运行多线程来获得任何性能改进?

标签 c++ multithreading c++11 parallel-processing

我有以下测试程序,它有一个简单的函数,可以找到我试图在多个线程中运行的素数(仅作为示例)。

#include <cstdio>
#include <iostream>
#include <ctime>
#include <thread>

void primefinder(void)
{
   int n = 300000;

   int i, j;
   int lastprime = 0;
   for(i = 2; i <= n; i++) {
      for(j = 2; j <= i; j++) {
           if((i % j) == 0) {
               if(i == j)
                   lastprime = i;
               else {
                   break;
               }
           }
      }
   }

   std::cout << "Prime: " << lastprime << std::endl;
}

int main(void)
{
   std::clock_t start;
   start = std::clock();

   std::thread t1(primefinder);
   t1.join();

   std::cout << "Time: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms" << std::endl;

   start = std::clock();

   std::thread t2(primefinder);
   std::thread t3(primefinder);
   t2.join();
   t3.join();

   std::cout << "Time: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms" << std::endl;
   return 0;
}

如图所示,我在 1 个线程中运行该函数一次,然后在 2 个不同的线程中运行一次。我使用 -O3 和 -pthread 用 g++ 编译它。我在 Linux Mint 18 上运行它。我有一个 Core i5-4670。我知道这取决于操作系统,但我非常希望这些线程能够并行运行。当我运行程序时,top 在使用 1 个线程时显示 100% CPU,在使用 2 个线程时显示 200% CPU。尽管如此,第二次运行的时间几乎是原来的两倍。

CPU 在运行程序时什么都不做。为什么这不能并行执行?

编辑:我知道两个线程都在做完全相同的事情。我选择 primerfinder 函数只是作为一个令人尴尬的并行的例子,所以当我在多个线程中运行它时,它应该实时花费同样长的时间。

最佳答案

在 C++ 中使用 std::clock 为并行程序计时是非常具有欺骗性的。在为程序计时时,我们关心两种类型的时间:wall time 和 cpu time。墙上的时间是我们都习惯的(想想墙上的时钟)。 CPU 时间本质上是您的程序使用了多少个 CPU 周期。 std::clock 返回 cpu 时间(这就是你除以 CLOCKS_PER_SEC 的原因)并且当有一个执行线程时 cpu 时间仅等于 wall time。如果一个程序可以 100% 并行运行(比如你的),那么 cpu time =(线程数)*(wall time)。因此,看到几乎两倍的时间正是您所期望的。

为了测量挂钟时间(这是您想要做的),我不知道有什么方法可以使用 STL 来完成。您可以使用 OpenMP 或 Boost 对其进行测量。

omp_get_wtime()

Boost Timer

由于您使用的是 linux,因此您经常使用的 g++ 版本很可能内置了 openmp 支持。

#include <omp.h>

const double startTime = omp_get_wtime();
..... //Work goes here

const double time = omp_get_wtime() - startTime;

您必须使用-fopenmp 进行编译

编辑:

正如 johnbakers 指出的那样,chrono 库确实有一个 wall clock

#include <chrono>

auto start = std::chrono::system_clock::now();
.... //Do some work

auto end = std::chrono::system_clock::now();
std::chrono::duration<double> diff = end - start;
std::cout << "Time: " << diff.count() << "(s)" << std::end;

那个与升压定时器的输出:

Boost: 121.685972s wall, 724.940000s user + 67.660000s system = 792.600000s CPU  (651.3%)
Chrono: 121.683(s)

关于c++ - 为什么我不能通过在 C++11 中运行多线程来获得任何性能改进?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38162550/

相关文章:

c++ - 调用转换函数后是否调用了移动构造函数?

C++ 包含文件混淆

c++ - 为什么 range::unique_copy 不能与 std::ostream_iterator 一起使用?

C# - QueuedTaskScheduler - threadCount 与 maxConcurrencyLevel

c - 使用Pthreads产生奇怪的编译错误

c++ - 从 lambda 返回值与声明位于同一行

c++ - 表达式语法错误 e2188、C++、Embarcadero、Count_If、

c++ - 初始化 COM 对象的问题

java - Android - 我应该在程序中使用 IntentService 还是 ThreadPool?

c++ - 根据长度对集合 <string> 进行排序