Ruben
Ruben

Reputation: 304

Programming strategy: how to use pointers or reference to increase speed or decrease memory use?

Suppose I have a function

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;
}

Now we see here the function rhobiweight that accepts two doubles, currently written as:

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) ;
}

The question is: how can I make use of pointers or references such that the x-value doesn't get copied? 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.

Upvotes: 3

Views: 143

Answers (2)

eerorika
eerorika

Reputation: 238311

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

By declaring the arguments as either pointers or references. But don't do that. Then you need to copy the address of the variable, which is just as slow, because the size of a double is same (or nearly same) as the size of a memory address. Not only that, but you need to dereference the pointer whenever you use it in the function. Or dereference it once and copy the value anyway.

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.

That would happen if the function is expanded inline by the optimizer. There is no standard way to force the compiler expand a function inline, but if the optimizer thinks it's advantageous, and you've enabled optimization, it will do that as long as the function is inlinable. To make the function inlinable, make sure that the definition is visible at the call site. A trivial way to do that is to declare the function inline.

Note that the peak memory use may actually be higher if many function calls are inlined.

Upvotes: 7

J&#248;rgen Fogh
J&#248;rgen Fogh

Reputation: 7656

TL;DR: Don't try to do this.

Full story:

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

If you are compiling your program with optimization turned on, the variables probably do not get copied anyway. Using pointers and/or references might just make things slower.

This leads me to a more important point: How do you even know that copying the values is taking a long time? Why would you expect that using pointers would take less time?

The way to optimize your code is to measure where the time is spent, then try to optimize that.

Upvotes: 6

Related Questions