UP | HOME

Exercise 37 solutions

Table of Contents

MATLAB

e37.m

matlabpool open
parfor i=1:10
%for i=1:10
  disp(['hello from iteration #',num2str(i)]);
end
matlabpool close

iPython

e37.py

# first at the shell prompt, in its own terminal, start a cluster:
#   ipcluster start -n 4
#
# then start ipython:
#   ipython --pylab

# import the parallel module
#
from IPython.parallel import Client

# create a client instance
#
rc = Client()

# show the client IDs
#
rc.ids

# create a DirectView object, use all engines
#
dview = rc[:]

# we'll use parallel "map" to implement the 10
# iterations in our for loop
# the first step is to define a function that does
# the computation that we want to parallelize
#
def mycomp(x):
    return "hello from iteration #" + str(x)

# now let's use the map() function to map the mycomp() function
# across the compute engines
#
parallel_result = dview.map(mycomp, range(10))

# now show the parallel results
#
for i,r in enumerate(parallel_result):
    print r

# after the program is finished, quit ipython
# and then CTRL-C stop the ipcluster

R

e37.R

library(foreach)
library(doMC)

registerDoMC(cores=4)

foreach (i=1:10, .combine=c) %dopar% {
	cat("hello from iteration",i,"\n")
}

C

e37.c

// compile with: gcc -o e37 e37.c -fopenmp

#include <stdio.h>
#include <omp.h>

int main(int argc, char *argv[]) {

  int i;

  #pragma omp parallel for
  for (i=0; i<10; i++) {
    printf("hello from iteration %d\n", i);
  }

  return 0;
}

Paul Gribble | fall 2014
This work is licensed under a Creative Commons Attribution 4.0 International License
Creative Commons License