C vs C++代码优化,用于简单的数组创建和i/o

Sha*_*ter 2 c++ compiler-construction io optimization

我一直试图说服我的朋友避免使用动态分配的数组并开始转移到STL向量.我给他发了一些示例代码来展示可以用STL和仿函数/生成器完成的一些事情:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

#define EVENTS 10000000

struct random_double {
  double operator() () { return (double)rand()/RAND_MAX; }
};  

int main(int argc, char **argv){

  std::vector<double> vd (EVENTS);

  generate(vd.begin(), vd.end(), random_double());
  copy(vd.begin(), vd.end(), std::ostream_iterator<double>(std::cout, "\n"));

  return 0;
} 
Run Code Online (Sandbox Code Playgroud)

他对此的回答,虽然他觉得它更优雅,但是他自己的代码更快(几乎是2倍!)这是他回答的C代码:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>

#define EVENTS 10000000

__inline double random_double() {
  return (double)rand()/RAND_MAX;
}


int main(int argc, char **argv){
  unsigned int i;
  double *vd;
  vd = (double *) malloc(EVENTS*sizeof(double));

  for(i=0;i<EVENTS;i++){ vd[i]=random_double(); }

  for(i=0;i<EVENTS;i++){ printf("%lf\n",vd[i]); }

  free(vd);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

所以我运行简单的计时测试,看看会发生什么,这就是我得到的:

> time ./c++test > /dev/null
real    0m14.665s
user    0m14.577s
sys     0m0.092s

> time ./ctest > /dev/null
real    0m8.070s
user    0m8.001s
sys     0m0.072s
Run Code Online (Sandbox Code Playgroud)

使用g ++的编译器选项是:g ++ -finline -funroll-loops.没什么特别的.谁能告诉我为什么C++/STL版本在这种情况下会变慢?瓶颈在哪里,我能用卖STL容器卖给我的朋友吗?

小智 19

几乎可以肯定的是iostream库与printf()的使用.如果要对算法计时,则应在循环外进行输出.


Tho*_*ini 17

使用printf:

  for (std::vector<double>::iterator i = vd.begin(); i != vd.end(); ++i)
     printf("%lf\n", *i);
Run Code Online (Sandbox Code Playgroud)

结果是:

koper@elisha ~/b $ time ./cpp > /dev/null
real    0m4.985s
user    0m4.930s
sys     0m0.050s
koper@elisha ~/b $ time ./c > /dev/null
real    0m4.973s
user    0m4.920s
sys     0m0.050s
Run Code Online (Sandbox Code Playgroud)

使用的标志: -O2 -funroll-loops -finline