c ++ std async:使用多个内核几乎没有效果

时间:2017-12-27 12:19:15

标签: multithreading c++11 asynchronous core

这个问题与:

有关

c++ std::async : faster on 4 cores compared to 8 cores

在上一个问题中,我想知道为什么有些代码会在4个内核而不是8个内核上运行得更快(答案:我的cpu有4个内核和8个线程)

现在我发现代码的速度或多或少与所使用的内核数量无关。

我在ubuntu 16.06上。 C ++ 11。英特尔®酷睿™i7-8550U CPU @ 1.80GHz×8

此处用于将计算时间与使用的核心数量进行基准比较的代码

#include <math.h>
#include <future>
#include <ctime>
#include <vector>
#include <iostream>

#define NB_JOBS 2000.0
#define MAX_CORES 8

// no special meaning to this function, 
// just uses some CPU
static bool _expensive(int nb_jobs){
  for(int job=0;job<nb_jobs;job++){
    float x = 0.6;
    bool b = true;
    double f = 1;
    for(int i=0;i<1000;i++){
      if(!b) f=-1;
      for(double j=1;j<2.0;j+=0.01) x+= f* pow(1.0/sin(x),j);
      b = !b;
    }
  }
  return true;
}

static double _duration(int nb_cores){

  std::clock_t begin = clock();

  int nb_jobs_per_core = rint ( NB_JOBS / (float)nb_cores );

  std::vector < std::future<bool> > futures;
  for(int i=0;i<nb_cores;i++){
    futures.push_back( std::async(std::launch::async,_expensive,nb_jobs_per_core));
  }
  for (auto &e: futures) {
    bool foo = e.get();
  }

  std::clock_t end = clock();

  double duration = double(end - begin) / CLOCKS_PER_SEC;
  return duration;

}


int main(){

  for(int nb_cores=1 ; nb_cores<=MAX_CORES ; nb_cores++){

    double duration = _duration(nb_cores);
    std::cout << nb_cores << " threads: " << duration << "\n";

  }

  return 0;

}

这里输出:

1 threads: 8.55817
2 threads: 8.76621
3 threads: 7.90191
4 threads: 8.4656
5 threads: 10.5494
6 threads: 11.6175
7 threads: 21.697
8 threads: 24.3621

使用核心似乎会产生边际影响。

让我烦恼的是CPU有4个核心。所以我期待程序在使用4个线程时运行(大约)4倍。它不是。

注意:“htop”显示程序预期的虚拟核心使用情况,即第一个核心使用100%,然后是2,......,以及结束8。

如果我更换:

futures.push_back( std::async(std::launch::async,[...]

by:

futures.push_back( std::async(std::launch::async|std::launch::deferred,[...]

然后我得到:

1 threads: 8.6459
2 threads: 8.69905
3 threads: 10.7763
4 threads: 11.4505
5 threads: 11.8426
6 threads: 10.4282
7 threads: 9.55181
8 threads: 9.05565

和htop显示在整个持续时间内只有1个虚拟核心被100%使用。

我做错了什么?

注意:我尝试了几个桌面,都有各种规格(nb核心和nb个线程),并观察到类似的东西。

0 个答案:

没有答案