[This article was first published on Adventures in Statistical Computing, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
This is a follow up to my previous post. There is a quicker way to compute the function I created (basic cumulative sum) in R.Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Instead of:
Use this:function f(x) {< o:p>sum = 0;< o:p>for (i in seq(1,x)) sum = sum + i< o:p>return(sum)< o:p>}< o:p>
If I time it, we see:f2 = function(x){< o:p>return(sum(seq(x)))< o:p>}< o:p>
Nice! Spread that across 3 CPUs and we can bring it down a bit:system.time( (out = apply(as.array(seq(10000)),1,f2)))< o:p>user system elapsed < o:p>0.35 0.05 0.39< o:p>
Not too shabby. How fast can we do this in SAS:system.time( (out2 = foreach(i=seq(0,9),.combine=’c’) %dopar% {< o:p>apply(as.array(seq(i*1000+1,(i+1)*1000)),1,f2)< o:p>}))< o:p>user system elapsed < o:p>0.02 0.00 0.26< o:p>
SAS on a single CPU is just as fast as R on 3. It’s not worth attempting to multi-thread this in SAS. The overhead would be too much as SAS/CONNECT is made for bigger problems.optionscmplib=work.fns;< o:p>procfcmp outlib=work.fns.fns;< o:p>function csum(x);< o:p>sum = 0;< o:p>do i=1to x;< o:p>sum = sum+i;< o:p>end;< o:p>return (sum);< o:p>endsub;< o:p>run;< o:p>data_null_;< o:p>doi=1 to 10000;< o:p>x = csum(i);< o:p>end;< o:p>run;< o:p>NOTE: DATA statement used (Total process time):< o:p>real time 0.24 seconds< o:p>cpu time 0.25 seconds< o:p>
So what about NumPY in Python? If we use the version compiled with MKL we ought to be able to do reduction in blazing fast time. MKL should use the SSE registers on the processor. Further, we’ll use the “fromfunction” method that lets us pass a lambda to the array creation method.
import numpy as np< o:p>import time as time< o:p>def f(x,y):< o:p>x = x +1< o:p>return(np.cumsum(x))< o:p>s = time.time()< o:p>y = np.fromfunction(f,(10000,1))< o:p>< o:p>el = time.time() – s< o:p>print “%0.6f” % el
0.002000
< o:p>
FAST.
To leave a comment for the author, please follow the link and comment on their blog: Adventures in Statistical Computing.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.