Download Programming on Parallel Machines - matloff
Transcript
152
8.8
CHAPTER 8. INTRODUCTION TO PARALLEL R
Parallelism Via Calling C from R
R does interface to C—R can call C and vice versa—so we can take advantage of OpenMP and CUDA from
R.
8.8.1
Calling C from R
In C, two-dimensional arrays are stored in row-major order, in contrast to R’s column-major order. For
instance, if we have a 3x4 array, the element in the second row and second column is element number 5
of the array when viewed linearly, since there are three elements in the first column and this is the second
element in the second column. Of course, keep in mind that C subscripts begin at 0, rather than at 1 as with
R. In writing your C code to be interfaced to R, you must keep these issues in mind.
All the arguments passed from R to C are received by C as pointers. Note that the C function itself must
return void. Values that we would ordinarily return must in the R/C context be communicated through the
function’s arguments, such as result in our example below.
As an example, here is C code to extract subdiagonals from a square matrix.7 The code is in a file sd.c:
1 # i n c l u d e <R . h> / / r e q u i r e d
2
3 / / arguments :
4 //
m: a s q u a r e m a t r i x
5 //
n : number o f rows / c o l u m n s o f m
6 //
k:
t h e s u b d i a g o n a l i n d e x −−0 f o r main d i a g o n a l , 1 f o r f i r s t
7 //
s u b d i a g o n a l , 2 f o r t h e second , e t c .
8 //
r e s u l t : space for the requested subdiagonal , returned here
9
10 v o i d s u b d i a g ( d o u b l e ∗m, i n t ∗n , i n t ∗k , d o u b l e ∗ r e s u l t )
11 {
12
i n t n v a l = ∗n , k v a l = ∗k ;
13
i n t s t r i d e = nval + 1;
14
f o r ( i n t i = 0 , j = k v a l ; i < n v a l −k v a l ; ++ i , j += s t r i d e )
15
r e s u l t [ i ] = m[ j ] ;
16 }
For convenience, you can compile this by rubnning R in a terminal window, which will invoke GCC:
1 % R CMD SHLIB s d . c
2 g c c −s t d = gnu99 −I / u s r / s h a r e / R / i n c l u d e
7
−f p i c
−g −O2 −c s d . c −o s d . o
I wish to thank my former graduate assistant, Min-Yu Huang, who wrote an earlier version of this function.