Sunday, February 10, 2013

Example 1: parfor in a simple Monte Carlo simulation

In this post I will use a simple Monte Carlo simulation that calculates the area of a quarter of a circle (see the figure below), using both a for and a parfor loop. The script is pretty straight-forward and I'm sure that anyone interested in parallel programming will have no problems understanding it.


As you will see the code will be identical, except for the type of loop, but we will see a clear difference between the time it takes for the code to run. Let's start by the script using the for loop:

When I execute the code I get:
>> Elapsed time is 15.142193 seconds.

Let's try again substituting for by parfor. The code is pretty much the same:

Now, when executed, we get:
>> Elapsed time is 6.140027 seconds.

As you can see the code is now about 2.5 times faster! This is a huge improvement. As we increase the number of points (N) the ratio between the two times will also increase. This is a property known as scalability. Below is a plot with the number of points used, N, and the time it takes to run the simulation with for and parfor.

As you can see this script sees a great improvement with a simple use of parallel functions. In fact all Monte Carlo simulations can be improved with parallel code! We can conclude that parallel computing only starts to pay off when we have a large number of simulations to run. It also stands for reason that the more labs we use the faster the code will run. Finally I will post the plot of the ratio between the time it takes for the script to run in series and in parallel. This is probably the most relevant piece of information that measures how successful your parallelization is.

As we can see the ratio converges to a value between 2.3 and 2.4. The convergence of the ratio is not a surprise. In general to improve this ratio alterations to the code are necessary. In our case there isn't much we can do because of the simplicity of the script!

In my next post I will post another good use of parfor in an equally simple script.

2 comments:

  1. Error using montecarlo_parfor (line 6)
    An UndefinedFunction error was thrown on the workers for 'hit'. This might be because the file containing 'hit' is not
    accessible on the workers. Use addAttachedFiles(pool, files) to specify the required files to be attached. See the
    documentation for 'parallel.Pool/addAttachedFiles' for more details.

    Caused by:
    Undefined function or variable 'hit'.

    ReplyDelete
    Replies
    1. I have also the same problem. How did you solve it? Thx

      Delete