c++ - 编程策略 : how to use pointers or reference to increase speed or decrease memory use?

标签 c++

假设我有一个函数

double tauscale(NumericVector x){
  int n = x.size();
  const double k = 2;
  double sc = 1.48*sqrt(median(x*x));
  double tauscale = 0.0;
  for(int i = 0 ; i < n ; ++i){
    tauscale = tauscale + rhobiweight(x(i)/sc,k);
  }
  return (1.0/n)*pow(sc,2)*tauscale;
}

现在我们在这里看到接受两个 double 的函数 rhobiweight,目前写成:

double rhobiweight(double x,double k = 2.0){
  double rho = 1.0;
  if(std::abs(x)<k){
    rho = 1.0-pow((1.0-pow(x/k,2)),3);
  }
  return rho/Erho(k) ;
}

问题是:如何使用指针或引用来避免 x 值被复制?理想情况下,计算时间和内存使用应该与我从未编写过 rhobiweight 相同,而是直接在 tauscale 中实现了这个函数。

最佳答案

how can I make use of pointers or references such that the x-value doesn't get copied?

通过将参数声明为指针或引用。但是不要那样做。然后你需要复制变量的地址,这同样很慢,因为 double 的大小与内存地址的大小相同(或几乎相同)。不仅如此,无论何时在函数中使用它,都需要取消对指针的引用。或者取消引用一次并复制值。

Ideally the computation time and memory use should be the same as if I had never written rhobiweight, but implemented this function directly in tauscale.

如果函数被优化器内联扩展,就会发生这种情况。没有强制编译器内联扩展函数的标准方法,但如果优化器认为它是有利的,并且您启用了优化,那么只要函数是可内联的,它就会这样做。要使函数可内联,请确保定义在调用站点可见。一种简单的方法是声明函数 inline

请注意,如果内联许多函数调用,峰值内存使用量实际上可能会更高。

关于c++ - 编程策略 : how to use pointers or reference to increase speed or decrease memory use?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34896296/

相关文章:

c++ - 成功时具有非零返回值的 WINAPI 方法

c++ - 如何构建自定义 libcurl 以仅支持 HTTP/HTTPS 协议(protocol)

c++ - 使用模板实现的通用类型容器

c++ - 在智能指针的取消引用值上调用 std::move()

c++ - 理解这种函数模板使用的问题

C++ 验证 float

c++ - 如何在头文件中组织代码实体?

c++ - 在 C++ 中创建 boost dynamic_bitset 的 vector

c++ - 如何从 C++ 中的另一个主函数调用 Google Tests

c++ - C++ 编译器如何处理这个初始化列表?