[R] Computing time when calling C functions - why does an extra function call induce such an overhead?

Prof Brian Ripley ripley at stats.ox.ac.uk
Sun Apr 13 15:23:18 CEST 2008


I've not seen any reposnse to this, probably because

-- this is not the list for C programming questions  (use R-devel)
-- there is no example provided for the times quoted.
-- the code is not compilable.

But I got a compiler warning on

   int *ipiv  = (int *) R_alloc((int) nrA, sizeof(int));

foo.c:8: warning: cast from pointer to integer of different size

(it should be *nrA) and that's most likely your error.  (BTW, using 
liberal casts like this is just stopping your tools helping you!)

The overhead of C function call is measured in nanosecs on modern systems, 
especially to functions in the same compilation unit.

On Thu, 10 Apr 2008, Søren Højsgaard wrote:

> Dear list,
>
> I am a little puzzled by computing time in connection with calling C 
> functions. With the function mysolve1 given below I solve Ax=B, where 
> the actual matrix operation takes place in mysolve2. Doing this 5000 
> times takes 3.51 secs. However, if I move the actual matrix inversion 
> part into mysolve1 (by uncommenting the two commented lines and skip the 
> call to mysolve2) then the computations take only 0.03 secs. Can anyone 
> tell me why there is such a "time-overhead" in introducing the extra 
> function call to mysolve2?
>
> I am on windows XP using R 2.6.1
>
> Best regards
> Søren
>
>
> SEXP mysolve1(SEXP Ain, SEXP Bin, SEXP tolin)
> {
>  int *Adims, *Bdims;
>  double tol = asReal(tolin);
>  SEXP A, B;
>  PROTECT(A = duplicate(Ain));
>  PROTECT(B = duplicate(Bin));
>  Adims = INTEGER(coerceVector(getAttrib(A, R_DimSymbol), INTSXP));
>  Bdims = INTEGER(coerceVector(getAttrib(B, R_DimSymbol), INTSXP));
>  int nrA, ncB;
>  double *Ap, *Bp;
>  nrA     = Adims[0];
>  ncB     = Bdims[1];
>  Ap      = REAL(A);
>  Bp      = REAL(B);
> /*   int info, *ipiv  = (int *) R_alloc(nrA, sizeof(int)); */
> /*   F77_CALL(dgesv)(&nrA, &ncB, Ap, &nrA, ipiv, Bp, &nrA, &info); */
>  mysolve2(Ap, &nrA, Bp, &ncB, &tol);
>  UNPROTECT(2);
>  return B;
> }
>
> void mysolve2(double *A, int *nrA, double *B, int *ncB, double *tolin)
> {
>  int info;
>  int *ipiv  = (int *) R_alloc((int) nrA, sizeof(int));
>  F77_CALL(dgesv)(nrA, ncB, A, nrA, ipiv, B, nrA, &info);
> }
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595


More information about the R-help mailing list