[R-SIG-Mac] Grand Central Dispatch (simple loop optimization)
Jan de Leeuw
deleeuw at stat.ucla.edu
Thu Sep 17 20:11:00 CEST 2009
****************** threads.c
*******************************************************
#include <math.h>
#include <dispatch/dispatch.h>
double do_work(double *, int , int);
void gcd_try (int *, int *, double *, double *);
void dgc_try (int *, int *, double *, double *);
void gcd_try (int *npowers, int *nlength, double *data, double
*results) {
dispatch_queue_t queue = dispatch_get_global_queue
(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply(*npowers, queue, ^(size_t i) {
results[i] = do_work(data, *nlength, i);
});
}
void dcg_try (int *npowers, int *nlength, double *data, double
*results) {
int i;
for (i = 0; i < *npowers; i++) {
results[i] = do_work(data, *nlength, i);
}
}
double do_work(double *data, int nlength, int power) {
int k; double s = 0.0;
for (k = 0; k < nlength; k++) {
s += pow(data[k],(double) power);
}
return(s);
}
****************** threads.R
*******************************************************
dyn.load("threads.so")
threads<-function(nlength,npowers,gcd=FALSE) {
set.seed(12345)
data<-rnorm(nlength)
results<-rep(0,npowers)
if (gcd)
aList<-.C("gcd_try",npowers=as.integer(npowers),nlength=as.integer
(nlength),data=as.double(data),results=as.double(results))
else
aList<-.C("dcg_try",npowers=as.integer(npowers),nlength=as.integer
(nlength),data=as.double(data),results=as.double(results))
return(aList$results)
}
**************************************************************************************
> system.time(threads(100000,1000,gcd=FALSE))
user system elapsed
8.967 0.004 8.971
> system.time(threads(100000,1000,gcd=TRUE))
user system elapsed
10.453 0.008 0.697
> system.time(threads(1000000,100,gcd=FALSE))
user system elapsed
3.698 0.013 3.712
> system.time(threads(1000000,100,gcd=TRUE))
user system elapsed
5.253 0.026 0.477
===
Jan de Leeuw; Distinguished Professor and Chair, UCLA Department of
Statistics;
Director: UCLA Center for Environmental Statistics (CES);
Editor: Journal of Multivariate Analysis, Journal of Statistical
Software;
US mail: 8125 Math Sciences Bldg, Box 951554, Los Angeles, CA 90095-1554
phone (310)-825-9550; fax (310)-206-5658; email: deleeuw at stat.ucla.edu
.mac: jdeleeuw ++++++ aim: deleeuwjan ++++++ skype: j_deleeuw
homepages: http://gifi.stat.ucla.edu ++++++ http://www.cuddyvalley.org
-------------------------------------------------------------------------------------------------
No matter where you go, there you are. --- Buckaroo Banzai
http://gifi.stat.ucla.edu/sounds/nomatter.au
More information about the R-SIG-Mac
mailing list