<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="http://www.r-bloggers.com/r-and-openmp-boosting-compiled-code-on-multi-core-cpu-s/"></div></div><div><a data-url="http://www.r-bloggers.com/r-and-openmp-boosting-compiled-code-on-multi-core-cpu-s/" data-counturl="http://www.r-bloggers.com/r-and-openmp-boosting-compiled-code-on-multi-core-cpu-s/" data-count="horizontal" data-text="R and openMP: boosting compiled code on multi-core cpu-s" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.parallelr.com/r-and-openmp-boosting-compiled-code-on-multi-core-cpu-s/"> Blog – ParallelR</a></strong>, and kindly contributed to <a rel="nofollow" href="http://www.r-bloggers.com/">R-bloggers)</a> </div>
<div><span>Share This: </span><a title="Share on Facebook" data-provider="facebook" target="_blank" rel="nofollow" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.parallelr.com%2Fr-and-openmp-boosting-compiled-code-on-multi-core-cpu-s%2F&t=R%20and%20openMP%3A%20boosting%20compiled%20code%20on%20multi-core%20cpu-s&%23038;s=100&%23038;p&%23091;url&%23093;=http%3A%2F%2Fwww.parallelr.com%2Fr-and-openmp-boosting-compiled-code-on-multi-core-cpu-s%2F&%23038;p&%23091;images&%23093;&%23091;0&%23093;=http%3A%2F%2Fwww.parallelr.com%2Fwp-content%2Fuploads%2F2016%2F05%2Fr-open.jpg&%23038;p&%23091;title&%23093;=R%20and%20openMP%3A%20boosting%20compiled%20code%20on%20multi-core%20cpu-s"><img title="Share on Facebook" alt="Facebook" src="http://i1.wp.com/www.parallelr.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/64x64/facebook.png?resize=32%2C32" data-recalc-dims="1"></a><a title="Share on Twitter" data-provider="twitter" target="_blank" rel="nofollow" href="http://twitter.com/share?url=http%3A%2F%2Fwww.parallelr.com%2Fr-and-openmp-boosting-compiled-code-on-multi-core-cpu-s%2F&text=Hey%20check%20this%20out"><img title="Share on Twitter" alt="twitter" src="http://i0.wp.com/www.parallelr.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/64x64/twitter.png?resize=32%2C32" data-recalc-dims="1"></a><a title="Share on Google+" data-provider="google_plus" target="_blank" rel="nofollow" href="https://plus.google.com/share?url=http%3A%2F%2Fwww.parallelr.com%2Fr-and-openmp-boosting-compiled-code-on-multi-core-cpu-s%2F"><img title="Share on Google+" alt="google_plus" src="http://i1.wp.com/www.parallelr.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/64x64/google_plus.png?resize=32%2C32" data-recalc-dims="1"></a><a title="Share on Reddit" data-provider="reddit" target="_blank" rel="nofollow" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.parallelr.com%2Fr-and-openmp-boosting-compiled-code-on-multi-core-cpu-s%2F&title=R%20and%20openMP%3A%20boosting%20compiled%20code%20on%20multi-core%20cpu-s"><img title="Share on Reddit" alt="reddit" src="http://i1.wp.com/www.parallelr.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/64x64/reddit.png?resize=32%2C32" data-recalc-dims="1"></a><a title="Pin it with Pinterest" data-provider="pinterest" target="_blank" rel="nofollow" href="http://pinterest.com/pin/create/button/?url=http%3A%2F%2Fwww.parallelr.com%2Fr-and-openmp-boosting-compiled-code-on-multi-core-cpu-s%2F&media=http%3A%2F%2Fwww.parallelr.com%2Fwp-content%2Fuploads%2F2016%2F05%2Fr-open.jpg&%23038;description=R%20and%20openMP%3A%20boosting%20compiled%20code%20on%20multi-core%20cpu-s"><img title="Pin it with Pinterest" alt="pinterest" src="http://i2.wp.com/www.parallelr.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/64x64/pinterest.png?resize=32%2C32" data-recalc-dims="1"></a><a title="Share on Linkedin" data-provider="linkedin" target="_blank" rel="nofollow" href="http://www.linkedin.com/shareArticle?mini=true&url=http%3A%2F%2Fwww.parallelr.com%2Fr-and-openmp-boosting-compiled-code-on-multi-core-cpu-s%2F&%23038;title=R%20and%20openMP%3A%20boosting%20compiled%20code%20on%20multi-core%20cpu-s"><img title="Share on Linkedin" alt="linkedin" src="http://i0.wp.com/www.parallelr.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/64x64/linkedin.png?resize=32%2C32" data-recalc-dims="1"></a><a title="Share by email" data-provider="mail" target="_blank" rel="nofollow" href="mailto:?subject=R%20and%20openMP%3A%20boosting%20compiled%20code%20on%20multi-core%20cpu-s&body=Hey%20check%20this%20out:%20http%3A%2F%2Fwww.parallelr.com%2Fr-and-openmp-boosting-compiled-code-on-multi-core-cpu-s%2F"><img title="Share by email" alt="mail" src="http://i0.wp.com/www.parallelr.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/64x64/mail.png?resize=32%2C32" data-recalc-dims="1"></a></div>
<h1>Introduction</h1>
<p>Sometimes you just need more speed. And sometime plain R does not provide it.</p>
<p>This article is about boosting your R code with C++ and openMP. OpenMP is a parallel processing framework for shared memory systems. This is an excellent way to use all the cpu cores that are sitting, and often just idling, in any modern desktop and laptop. Below, I will take a simple, even trivial problem—ML estimation of normal distribution parameters—and solve it first in R, thereafter I write the likelihood function in standard single-threaded C++, and finally in parallel using C++ and openMP. Obviously, there are easier ways to find sample mean and variance but this is not the point. Read it, and try to write your own openMP program that does something useful!</p>
<h1>R for Simplicity</h1>
<p>Assume we have a sample of random normals and let’s estimate the parameters (mean and standard deviation) by Maximum Likelihood (ML). We start with pure R. The log-likelihood function may look like this:</p>
<pre>
llR &lt;- function(par, x) {
   mu &lt;- par[1]
   sigma &lt;- par[2]
   sum(-1/2*log(2*pi) - log(sigma) - 1/2*((x - mu)^2)/sigma^2)
}
</pre>
<p>Note that this code is fully vectorized (<code>(x-mu)</code> is written with no explicit loop) and hence very fast. Obviously, this is a trivial example, but it is easy to understand and parallelize.</p>
<p>Now generate some data</p>
<pre>
x &lt;- rnorm(1e6)
</pre>
<p>and start values, a bit off to give the computer more work:</p>
<pre>
start &lt;- c(1,1)
</pre>
<p>Estimate it (using maxLik package):</p>
<pre>
library(maxLik)
system.time(m &lt;- maxLik(llR, start=start, x=x))
</pre>
<pre>   user system elapsed
  2.740  0.184   2.931
</pre>
<pre>
summary(m)
</pre>
<pre>--------------------------------------------
Maximum Likelihood estimation
Newton-Raphson maximisation, 6 iterations
Return code 2: successive function values within tolerance limit
Log-Likelihood: -1419125
2 free parameters
Estimates:
Estimate Std. error t value Pr(> t)
[1,] 0.0010318 0.0010001 1.032 0.302
[2,] 1.0001867 0.0007072 1414.236 &lt;2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
--------------------------------------------
</pre>
<p>The code runs 2.6s on an i5-2450M laptop using a single cpu core.</p>
<p>First, let’s squeeze more out of the R code. Despite being vectorized, the function can be improved by moving the repeated calculations out of the (vectorized) loop. We can re-write it as:</p>
<pre>
llROpt &lt;- function(par, x) {
   mu &lt;- par[1]
   sigma &lt;- par[2]
   N &lt;- length(x)
   -N*(0.5*log(2*pi) + log(sigma)) - 0.5*sum((x - mu)^2)/sigma^2
}
</pre>
<p>Now only <code>(x - mu)^2</code> is computed as vectors. Run it:</p>
<pre>
library(maxLik)
system.time(m &lt;- maxLik(llROpt, start=start, x=x))
</pre>
<pre>   user  system elapsed
  0.816   0.000   0.818 
</pre>
<p>You see—just a simple optimization gave a more than three–fold speed improvement! I don’t report the results any more, as those are virtually identical.</p>
<h1>C for Speed</h1>
<p>Now let’s implement the same function in C++. R itself is written in C, however there is an excellent library, Rcpp, that makes integrating R and C++ code very easy. It is beyond the scope of this post to teach readers C and explain the differences between C and C++. But remember that Rcpp (and hence C++) offers a substantially easier interface for exchanging data between R and compiled code than the default R API. Let’s save the log-likelihood function in file loglik.cpp. It might look like this:</p>
<pre>
#include &lt;cmath>
#include &lt;Rcpp.h>
 
using namespace Rcpp;
 
RcppExport SEXP loglik_opt(SEXP s_beta, SEXP s_x) {
    NumericVector x(s_x);
    NumericVector beta(s_beta);
    // make Rcpp vector out of R SEXP
    double mu = beta[0];
    // first element is 0 in C++
    double sigma = beta[1];
    double ll = 0;
    for(int i = 0; i &lt; x.length(); i++) {
        ll -= (x[i] - mu)*(x[i] - mu);
    }
    ll *= 0.5/sigma/sigma;
    ll -= (0.5*log(2*M_PI) + log(sigma))*x.length();
    NumericVector result(1, ll);
    // create 'numeric' vector of length 1, filled with
    // ll values
    return result;
}
</pre>
<p>The function takes two parameters, <code>s_beta</code> and <code>s_x</code>. These are passed as R general vectors, denoted <code>SEXP</code> in C. As SEXP-s are complicated to handle, the following two lines transform those to ‘NumericVector’s, essentially equivalent to R ‘numeric()’. The following code is easy to understand. We loop over all iterations and add (x[i] – mu)^2. Loops are cheap in C++. Afterwards, we add the constant terms only once. Note that unlike R, indices in C++ start from zero.</p>
<p>This program must be compiled first. Normally the command</p>
<pre>
R CMD SHLIB loglik.cpp
</pre>
<p>takes care of all the R-specific dependencies, and if everything goes well, it results in the DLL file. Rcpp requires additional include files which must be specified when compiling, the location of which can be queried with <code>Rcpp:::CxxFlags()</code> command in R, or as a bash one-liner, one may compile with</p>
<pre>
PKG_CXXFLAGS=$(echo 'Rcpp:::CxxFlags()'| R --vanilla --slave) R CMD SHLIB loglik.cpp
</pre>
<p>Now we have to create the R-side of the log-likelihood function. It may look like this:</p>
<pre>
llc &lt;- function(par, x) {
   library(Rcpp)
   dyn.load(&quot;loglik.so&quot;) # extension '.so' is platform-specific!
   res &lt;- .Call(&quot;loglik&quot;, par, x)
   res
}
</pre>
<p>It takes arguments ‘par’ and ‘x’, and passes these down to the DLL. Before we can invoke (<code>.Call</code>) the compiled code, we must load the DLL. You may need to adjust the exact name according to your platform here. Note also that I haven’t introduced any security checks neither at the R nor the C++ side. This is a quick recipe for crashing your session, but let’s avoid it here in order to keep the code simple.</p>
<p>Now let’s run it:</p>
<pre>
system.time(m &lt;- maxLik(llc, start=start, x=x))
</pre>
<pre>   user  system elapsed
  0.896   0.020   0.913 
</pre>
<p>The C code runs almost exactly as fast as the optimized R. In case of well vectorized computations, there seems to be little scope for improving the speed by switching to C.</p>
<h1>Parallelizing the code on multicore CPUs</h1>
<p>Now it is time to write a parallel version of the program. Take the C++ version as the point of departure and re-write it like this:</p>
<pre>
#include &lt;cmath>
#include &lt;Rcpp.h>
#include &lt;omp.h>
 
using namespace Rcpp;
 
RcppExport SEXP loglik_MP(SEXP s_beta, SEXP s_x, SEXP s_nCpu) {
    NumericVector x(s_x);
    NumericVector beta(s_beta);
    int n_cpu = IntegerVector(s_nCpu)[0];
    double mu = beta[0];
    double sigma = beta[1];
    double ll = 0;
    omp_set_dynamic(0);         // Explicitly disable dynamic teams
    omp_set_num_threads(n_cpu); // Use n_cpu threads for all
                                // consecutive parallel regions
#pragma omp parallel
    {
        double ll_thread = 0;
#pragma omp for	
        for(int i = 0; i &lt; x.length(); i++) {
            ll_thread -= (x[i] - mu)*(x[i] - mu);
        }
#pragma omp critical
        {
            ll += ll_thread;
        }
    }
    ll *= 0.5/sigma/sigma;
    ll -= (0.5*log(2*M_PI) + log(sigma))*x.length();
    NumericVector result(1, ll);
    return result;
}
</pre>
<p>The code structure is rather similar to the previous example. The most notable novelties are the ‘#pragma omp’ directives. These tell the compiler to insert parallelized code here. Not all compilers understand it, and others may need special flags, such as <code>-fopenmp</code> in case of gcc, to enable openMP support. Otherwise, gcc just happily ignores the directives and you will get a single-threaded application. The likelihood function also includes the argument <em>n_Cpu</em>, and the commands <code>omp_set_dynamic(0)</code> and <code>omp_set_num_threads(n_cpu)</code>. This allows to manipulate the number of threads explicitly, it is usually not necessary in the production code.</p>
<p>For compiling the program, we can add <code>-fopenmp</code> to our one-liner above:</p>
<pre>
PKG_CXXFLAGS=&quot;$(echo 'Rcpp:::CxxFlags()'| R --vanilla --slave) -fopenmp&quot; R CMD SHLIB loglikMP.cpp
</pre>
<p>assuming it was saved in “loglikMP.cpp”. But now you should seriously consider writing a makefile instead.</p>
<p>We use three openMP directives here:</p>
<pre>

#pragma omp parallel
{
/* code block */
}

</pre>
<p>This is the most important omp directive. It forces the code block to be run in multiple threads, by all threads simultaneously. In particular, variable <em>ll_thread</em> is declared in all threads separately and is thus a thread-specific variable. As OMP is a shared-memory parallel framework, all data declared before <em>#pragma omp parallel</em> is accessible by all threads. This is very convenient as long as we only read it.</p>
<p>The last directive is closely related:</p>
<pre>

#pragma omp critical
{
/* code block */
}

</pre>
<p>This denotes a piece of threaded code that must be run by only one thread simultaneously. In the example above all threads execute <code>ll += ll_thread</code>, but only one at a time, waiting for the previous thread to finish if necessary. This is because now we are writing to shared memory: variable <em>ll</em> is defined before we split the code into threads. Allowing multiple threads to simultaneously write in the same shared variable almost always leads to trouble.</p>
<p>Finally,</p>
<pre>
#pragma omp for
for(...) { /* code block */ }

</pre>
<p>splits the for loop between threads in a way that each thread will only go through a fraction of the full loop. For instance, in our case the full loop goes over 1M observations, but in case of 8 threads, each will receive only 125k. As the compiler has to generate code for this type of loop sharing, parallel loops are less flexible than ordinary single-threaded loops. For many data types adding the thread–specific values we did with <code>#pragma omp critical</code> can be achieved directly in the loop by specifying <code>#pragma omp parallel for reduction(+:ll)</code> instead.</p>
<p>As all the parallel work is done at C level, the R code remains essentially unchanged. We may write the corresponding loglik function as</p>
<pre>
llcMP &lt;- function(par, nCpu=1, x) {
   library(Rcpp)
   dyn.load(&quot;loglikMP.so&quot;)
   res &lt;- .Call(&quot;loglik_MP&quot;, par, x, as.integer(nCpu))
   res
}
</pre>
<p>How fast is this?</p>
<pre>
system.time(m &lt;- maxLik(llcMP, start=start, nCpu=4, x=x))
</pre>
<pre>   user  system elapsed
  0.732   0.016   0.203 
</pre>
<p>On 2-core/4-thread cpu, we got a more than four–fold speed boost. This is impressive, given the cpu does have 2 complete cores only. Obviously, the performance improvement depends on the task. This particular problem is embarrasingly parallel, the threads can work completely independent of each other.</p>
<h1>Timing Examples</h1>
<p>As an extended timing example, we run all the (optimized) examples above using a Xeon-L5420 cpu with 8 cores, single thread per core. The figure below depicts the compute time for single-threaded R and C++ code, and for C++/openMP code with 8 threads, as a function of data size.</p>
<p><img alt="timings" class="wp-image-1028" src="http://i0.wp.com/www.parallelr.com/wp-content/uploads/2016/07/timings-1-1024x585.png?resize=456%2C260" data-recalc-dims="1"></p>
<p>The figure reveals several facts. First, for non-parallelized code we can see that</p>
<ol>
<li>Optimized R and C++ code are of virtually identical speed.</li>
<li>compute time grows linearily in data size.</li>
</ol>
<p>For openMP code the figure tells</p>
<ol start="3">
<li>openMP with 8 threads is substantially slower for data size less than about 100k. For larger data, multi-threaded approach is clearly faster.</li>
<li>openMP execution time is almost constant for data size up to 4M. For larger data vectors, it increases linearily. This suggests that for smaller data size, openMP execution time is dominated by thread creation and management overheads, not by computations.</li>
</ol>
<p>Finally, let’s compare the computation times for different number of threads for 8M data size.</p>
<p><img alt="timings_n" class="wp-image-1031" src="http://i2.wp.com/www.parallelr.com/wp-content/uploads/2016/07/timings_n-2-1024x585.png?resize=456%2C261" data-recalc-dims="1"></p>
<p>The figure shows the run time for single threaded versions of the code (R and C), and multi-threaded openMP versions with 1 to 9 threads (OMP.1 to OMP.9).</p>
<ol>
<li>More cpus give us shorter execution times. 1-thread OMP will run almost 1.7 times slower than 8-threaded version (3.9 and 2.3 s respectively).</li>
<li>The gain of more cpu cores working on the problem levels off quickly. Little noticeable gain is visible for more than 3 cores. It indicates that the calculations are only partly limited by computing-power. Another major bottleneck may be memory speed.</li>
<li>Last, and most strikingly, even the single threaded OMP version of the code is 4.8 times faster than single-threaded C++ version with no OMP (18.6 and 3.9 s respectively)! This is a feature of the particular task, the compiler and the processor architecture. OMP parallel for–loops allow the compiler to deduce that the loops are in fact independent, and use faster SSE instruction set. This substantially boosts the speed but requires more memory bandwidth.</li>
</ol>
<h1>Conclusion</h1>
<p>With the examples above I wanted to show that for many tasks, openMP is not hard to use. If you know some C++, parallelizing your code may be quite easy. True, the examples above are easy to parallelize at R-level as well, but there are many tasks where this is not true.</p>
<p>Obviously, in the text above I just scratched the surface of openMP. If you consider using it, there are many excellent sources on the web. Take a look!</p>
<p>I am grateful to Peng Zhao for explaining the parallel loops and SSE instruction set.</p>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="http://www.r-bloggers.com/r-and-openmp-boosting-compiled-code-on-multi-core-cpu-s/"></div></div><div><a data-url="http://www.r-bloggers.com/r-and-openmp-boosting-compiled-code-on-multi-core-cpu-s/" data-counturl="http://www.r-bloggers.com/r-and-openmp-boosting-compiled-code-on-multi-core-cpu-s/" data-count="vertical" data-text="R and openMP: boosting compiled code on multi-core cpu-s" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.parallelr.com/r-and-openmp-boosting-compiled-code-on-multi-core-cpu-s/"> Blog – ParallelR</a></strong>.</div>
<hr>
<a rel="nofollow" href="http://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="http://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="http://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="http://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="http://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="http://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="http://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="http://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="http://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="http://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="http://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="http://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="http://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="http://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="http://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="http://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="http://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="http://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="http://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/CPBWY3Eo-VQ"></a></div>