Equivalent of inc(x) or x++ in R
Let try different solutions to mimic C operand ++ to have the most efficient.
n <- as.integer(1)
system.time(for (i in 1:100000) n <- n + 1)
n <- as.numeric(1)
system.time(for (i in 1:100000) n <- n + 1)
n <- as.double(1)
system.time(for (i in 1:100000) n <- n + 1)
n <- as.integer(1)
system.time(for (i in 1:100000) n <- n + 1)
n <- as.numeric(1)
system.time(for (i in 1:100000) n <- n + 1)
n <- as.double(1)
system.time(for (i in 1:100000) n <- n + 1)
No change:
utilisateur système écoulé
0.035 0.000 0.036
Not let do a function inc():
inc <- function(x) eval.parent(substitute(x <- x + 1))
n <- as.integer(1)
system.time(for (i in 1:100000) inc(n))
It is ten times slower:
utilisateur système écoulé
0.470 0.005 0.477
Using the Hmisc package:
require(Hmisc)
n <- as.integer(1)
system.time(for (i in 1:100000) inc(n) <- 1 )
It is only 3 times slower:
utilisateur système écoulé
0.150 0.001 0.151
And using a C function:
In file inc.c:
#include <R.h>
void inc(int *x)
{
x[0]++;
}
Enter these in R console:
system('R CMD SHLIB inc.c')
dyn.load("inc.so")
n <- as.integer(1)
system.time(for (i in 1:100000) n <- .C("inc", n=n)$n)
The result is the worst of all the tries !
utilisateur système écoulé
31.783 3.996 36.163
In conclusion n <- n + 1 is still the best !
Commentaires
Enregistrer un commentaire