Rturbo/P
Home > Documentation > Code Examples 

Code Examples 

Parallel simulation:

Using the thread statement: 

Suppose you have a function mysim( S ), which returns a vector with S simulated repicates of a statistic. In P you can easily perform computations in parallel:
 
res = numeric( 10000 )
thread res[1:4999] = mysim( 5000 )
thread res[5000:9999] = msyim( 5000 )
sync
 
That's all!
 
 
Parallelized for loops:
 
Many simulations conducted in R have the form
 
mysim = function( simsize ) {
  res = numeric( simsize )
  for ( s in (1:simsize) ) {
    x = rnorm( n, 0, 1 )  
    res[s] = calc_stat( x )
  }
  return( res )
}
 
In Rturbo/P this can be easily calculed concurrently using all availables cores on your computer: Simply tell the system that res is a shared variable and put the keyworkd parallel in front of the for.
 
mysim = function( simsize ) {
  res = numeric( simsize )
  shared( res )
  parallel for ( s in (1:simsize) ) {
    x = rnorm( n, 0, 1 )  
    res[s] = calc_stat( x )
  }
  return( res )
}

Isn't that simple?

 

Using references (pointers):

 
References to objects are known in many languages, e.g. C or JAVA. They have been implemented in P, since they provide an important vehicle for high-performance computations. In R and P, arguments to function calls are passed by value. This means, a function receives a copy of the arguments. If the arguments are large matrices and the function is invoked many times, a huge number of unnecessary memory operations occurs. Look at the following example:
 
 
# this function computes the arithmetic mean of x[1], ..., x[i]
# in a real application, the code for myfunc can be very long,
# thus justifying to put it in a function.

myfunc = function( x, i ) {

  res = mean( x[1:i] )

  return( res )
}

# apply the function func to x[1], ..., x[i], i = 1, ..., n
# return the result as a vector of length n

mystat = function( x ) {

  n = length( x )

  for ( i in (1:n) ) {
    res[i] = myfunc( x, i )
  }
  return( res )
}
 
If mystat is applied to vector of length 1000, the vector x is copied 1000 times and those copies are used by myfunc. If we replace the single line
 
    res[i] = myfunc( x, i )
 
by
 
    res[i] = myfunc( &x, i )

the program will be substantially faster. Now a reference (pointer) to x is given to the function myfunc avoiding those unnecessary memory operations.
 
(For further code examples download P and study the example programs).