Friday, January 13, 2006

C++ versus MatLab

After a discussion with the MultimodalPainter senior students regarding performance of RGB to HSV conversion algorithm in MatLab, I decided to compare the time needed in MatLab and C++ compiled files to run a very simple algorithm. To that end, I wrote the following pseudo-code in both programming languages:

Function SimpleCycle(Matrix M) {
ACC is a dummy variable
ACC = 0

for each line L in M
for each column C in M
ACC = ACC + value stored in M(L,C)

return ACC

Using as input an integer matrix M with size 350x350 , this simple algorithm proved to be a good choice to show the performance differences in MatLab and C++. Below are the results obtained in informal tests:

Based on these results I made no comments. I just want to point out that the test programs took less than five minutes to write and run from scratch in MatLab, but more than twenty minutes in C++ (including the matrix creation and time measuring routines incorporation).


vepachnh said...
This comment has been removed by the author.
vepachnh said...

hi, do you think for monte carlo simulations also MATLAB would underperform when compared to C++. I am trying to decide on either MATLAB or C++ to use.

Nishanth Vepachedu

Alfredo Ferreira said...

Note that loops are particularly slow in Matlab. That's why in this comparison the C++ code outperformed so much its Matlab counterpart. Considering that implementation of a Monte Carlo simulation in Matlab can be done without cycles and with fewer (and simpler) lines of code, I will probably suggest that you use Matlab.

Alfredo Ferreira

Anhar said...

Interesting informal test, I've always like Matlab, C++ (yay!), and Fortran (double yay!).

The interesting thing to note is the history of Matlab, orginally created to give access to LINPACK (written in FORTRAN) and then re-written in C.

Of course Matlab has grown into something massive since then,

So if you want to build some very specific algorithm/application/program you have to go the full blown programming language route (eg C++, C, FORTRAN), but if you want to do R&D and experimentations then Matlab can't be beat.

Anhar Hussain Miah

Alfredo Ferreira said...

I agree with Anhar. To test new algorithms and ideas, Matlab is the best tool. Then, if it works and one wants to make something out of it, one should switch to a "real" programming language.

Will Dwinnell said...

I think it'd be much more instructive to have the benchmark performing some interesting task, as the two tools are used in practice.

Also, a big difference between MATLAB an languages like C++ is how often loops are even used. People frequently remark that "loops are slow" in MATLAB. The other half of that reality is that, in MATLAB, explicit loops are less frequently used.

I run data mining analysis on desktop hardware (4 cores), and find MATLAB maintains a good pace.