我以两种方式运行完全相同的代码:使用g++
编译器编译它,然后使用R
从Rcpp
调用它。事实证明,当我通过R
运行它时运行速度快了近4倍。
为什么会这样?是因为Rcpp
使用的编译器不同吗?
这是我在c++
中运行的代码:
#include <iostream>
#include <nlopt.hpp>
#include <time.h>
using namespace std;
int main()
{
//--------------------------------//
// Initialization //
//--------------------------------//
// Grid for x
const int nx = 60000;
float xgrid[nx];
const float xstep = 4 /(nx - 1);
float it = 0;
for(int i = 0; i < nx; i++){
xgrid[i] = it*xstep;
it++;
}
// Initialize value function V
size_t sizeV = nx*sizeof(float);
float *V;
V = (float *)malloc(sizeV);
//--------------------------------//
// Computation //
//--------------------------------//
// Variables for computation time
double t0 = clock();
double t = t0;
float utility;
float VV = pow(-10.0,5.0);
for(int ix = 0; ix<nx; ix++){
VV = pow(-10.0,5.0);
for(int ixp = 0; ixp < nx; ixp++){
utility = (xgrid[ix] + 1 - xgrid[ixp])*(xgrid[ix] + 1 - xgrid[ixp]);
if(utility >= VV){
VV = utility;
}
}
V[ix] = VV;
}
t = clock() - t0;
cout << "Time: " << ((float)t)/CLOCKS_PER_SEC << " seconds." << endl;
return 0;
}
要运行它,我使用:
g++ Cpp_main.cpp -o Cpp_main
Rcpp
中的代码是:
#include <iostream>
#include <nlopt.hpp>
#include <time.h>
using namespace std;
// [[Rcpp::export]]
vector<double> value(int nx){
//--------------------------------//
// Grid creation //
//--------------------------------//
float xgrid[nx];
const float xstep = 4 /(nx - 1);
float it = 0;
for(int i = 0; i < nx; i++){
xgrid[i] = it*xstep;
it++;
}
// Initialize value function V
vector<double> V;
V.resize(nx);
//--------------------------------//
// Computation //
//--------------------------------//
// Variables for computation time
double t0 = clock();
double t = t0;
float utility;
float VV = pow(-10.0,5.0);
for(int ix = 0; ix<nx; ix++){
VV = pow(-10.0,5.0);
for(int ixp = 0; ixp < nx; ixp++){
utility = (xgrid[ix] + 1 - xgrid[ixp])*(xgrid[ix] + 1 - xgrid[ixp]);
if(utility >= VV){
VV = utility;
}
}
V[ix] = VV;
}
t = clock() - t0;
cout << "Time: " << ((float)t)/CLOCKS_PER_SEC << " seconds." << endl;
return V;
}
我从R
打电话给:
library("Rcpp")
sourceCpp("Rcpp_main.cpp")
# Grid for x
nx = 60000;
V = value(nx);
c++
中的运行时间是Rcpp
中运行时间的两倍。任何线索为什么会发生这种情况?
答案 0 :(得分:7)
只是看着你的main()
,我们就明白了:
edd@rob:/tmp/soQ$ g++ -o main main.cpp
edd@rob:/tmp/soQ$ ./main
Time: 8.42708 seconds.
edd@rob:/tmp/soQ$ g++ -o main -O3 -march=native main.cpp
edd@rob:/tmp/soQ$ ./main
Time: 1.59151 seconds.
edd@rob:/tmp/soQ$
这已经是5.3的一个因素,也是我在-O3
影响的一段时间内见过的最奇怪的例子之一。
对于R,我得到的时间与相同,因为R默认使用-O3 。
R> Rcpp::sourceCpp("/tmp/soQ/rcppfunction.cpp")
R> V <- value(60000)
Time: 1.65224 seconds.
R>
所以这里没有真正的谜。你使用了不同的选项,这很重要。