R调用C++函数

R语言虽然在数据统计和绘图方面有着很大的优势,但是运行速度慢是它最大的缺点,特别是针对数据量大的情况。利用C++底层运行速度优势,使用R语言调用C++函数可以有效的弥补R的这一个缺陷。

【1】在RStudio中新建c++file,添加代码如下:

#include <Rcpp.h>
using namespace Rcpp;
#include <string>
using namespace std;


//[[Rcpp::export]]
void hello(int n)
{
  for(int i=0;i<n;i++)
  {
    cout<<i;
  }
  cout<<endl;
}


/***
 hello("World");
 */

【2】新建RScript文件,添加代码如下:

library(Rcpp)
sourceCpp("F:\\R\\R数据的输入\\demoCpp.cpp")

print("C++ Function:")
system.time(hello(1000000))

myfun<-function(i)
{
  for(i in c(1:i))
  {
    print(i)
  }
}

print("R Function:")
system.time(myfun(1000000))

【3】比较C++函数和R函数运行时间,得到如下结果:

C++ Function:

用户    系统    流逝

3.16   3.25     3.00

R Function:

用户         系统        流逝

124.66    0.03       125.59




猜你喜欢

转载自blog.csdn.net/u010757019/article/details/52397829