Why does it take MATLAB so long to print hello world?

I apologize in advance for the formatting -- this forum post editor does not conform to the CommonMark standard, and thus I cannot properly share non-MATLAB code snippets. A distinct font will have to do until MathWorks adds support for basic Markdown features. EDIT: Somebody ninja-edited my question to get rid of the distinct font. No font will have to do, now. Seriously -- how do you guys discuss anything involving terminal use in this forum???
It takes MATLAB ~2.6 seconds to print "Hello, World!" from the command line:
$ time matlab -nojvm -noFigureWindows -nodisplay -batch "disp('Hello, World!')" Hello, World!
real 0m2.601s
user 0m2.645s
sys 0m0.267s
For comparison, that's 90x longer than the time it takes to read from stdin, compile, run, delete, and echo to stdout the equivalent C program:
$ time echo $(gcc -xc - <<< '#include "stdio.h"
int main() { printf("Hello, World!\n"); return 0; } ' && ./a.out && rm a.out) Hello, World!
real 0m0.029s
user 0m0.025s
sys 0m0.004s
It's also 170x longer than it takes to perform the Python equivalent:
$ time python3 -c "print('Hello, World!')"
Hello, World!
real 0m0.015s
user 0m0.012s
sys 0m0.004s
Why does MATLAB seem to take hundreds of times longer than it needs to in order to run a simple "Hello, World!" application?

9 Comments

What is your use case for which this matters? Often these sorts of questions have better solutions.
Even more often, these sorts of questions are just bad-faith slams against MATLAB, with no actual interest in solving a problem.
There are plenty of valid reasons for executing MATLAB commands outside of MATLAB's REPL. One of which is the abysmal parallel performance. parfor loops usually end up using about 38% of the CPU maximum for a ~3x speedup on 8 threads, for example. Before you ask, the (Monte-Carlo) simulations indeed ran long enough for the prospective benefits of multithreading to outweigh the overhead. It's a shame that with MATLAB they don't. Thus, we have to resort to hacks like this alongside something like gnu parallel to get things done in a reasonable amount of time.
@Matthew Elmer: I wanted to dig in a bit into this comment:
"Before you ask, the (Monte-Carlo) simulations indeed ran long enough for the prospective benefits of multithreading to outweigh the overhead."
By default, parallel workers are single-threaded, so if your code utilizes multi-threading, you will want to potentially change the number of threads (NumThreads) that the parallel workers have access to.
@Sam Marshalik then what does this bit in the documentation of parpool mean?
> With default preferences, MATLAB® starts a pool on the local machine with one worker per physical CPU core
@Matthew Elmer: I can clarify what that means. We recommend a 1 to 1 ratio between the number of parallel workers you strart and the number of physical cores available on the machine. So, if you have an 8 core CPU, we would recommend to start a pool of 8 workers. If you do not specify, I believe MATLAB should start a pool with a size that matches your number of physical cores (like the quote you mentioned). I always encourage people to specify their pool size so there are no surpises.
When working with workers and threads, follow this recipe:
Number of workers * number of threads that each worker has access to =< Number of Physical Cores
For example, if I have a parfor loop that includes a multi-threaded function, I could run multiple parfor iterations at the same time, by starting a pool of 2 workers and giveeach worker access to 4 threads:
>> c = parcluster("Processes");
>> c.NumThreads = 4;
>> c.parpool(2)
Hopefully that helps clarify things.
So the defaults should have produced enough workers for 100% CPU utilization, but they didn't. To get this comment section back on track: That's the problem, and that's why running MATLAB instances from the command line is a valid use case.
To insert non-MATLAB code in postings, as code for people to be able to use the Copy button to copy the code to execute on their own machines:
Click on the editor '>' toolbar button, in the 'CODE' section of the toolbar. Paste the code in to the region the editor created. If the editor automatically indented the code and you do not want the automatically formatted version, then after the paste, press control-Z : that will undo the automatic formatting.
To insert anything in postings as a mix of code and output for people to look at, without the expectation that they will want to copy it for execution on their own machines:
Click on the rightmost icon in the toolbar 'INSERT' section -- the one that looks like a stack of 4 lines. Paste the code/output in to the region the editor created. If it automatically formatted in a way you do not like, then press control-Z to undo the formatting.
Note: if you have already entered code into the editor as regular text, then you can highlight the code with your mouse, and then click on the '>' button and the text will be converted to a code region; you might need to control-Z to undo formatting.
@Walter Roberson Please post an example that includes correctly-syntax-highlighted Python, along with an example that contains simple monospace text without paragraph spacing between newlines.
Jon
Jon on 15 Sep 2023
Edited: Jon on 15 Sep 2023
@Matthew Elmer While I understand that you would like to be able to more easily post nicely formatted code in other languages, I think the currently implemented "Code" button is mainly intended for people to post MATLAB code as this is the focus of MATLAB answers.
I haven't really seen too many instances where people have had questions where it was important to them to post nicely formatted code in other computer languages. So if this is short coming of the MATLAB Answers site, I don't think it affects that many users.
I find sites like Stack Overflow are more oriented to general programming issues and go there for non MATLAB specific questions.

Sign in to comment.

Answers (3)

What MATLAB commands did you issue from the command line? What you gave does not work:
>> $ time matlab -nojvm -noFigureWindows -nodisplay -batch "disp('Hello, World!')"
$ time matlab -nojvm -noFigureWindows -nodisplay -batch "disp('Hello, World!')"
Error: Invalid text character. Check for unsupported symbol, invisible character, or pasting of non-ASCII
characters.
>> time matlab -nojvm -noFigureWindows -nodisplay -batch "disp('Hello, World!')"
Incorrect number or types of inputs or outputs for function 'time'.
Was it from a console window prompt instead of the command prompt in MATLAB? If it was, it looks like you may be launching the full MATLAB program, just with no user interface shown, which of course will take more time than if MATLAB is already up and running. You will of course have lots of overhead in that case. Maybe you should test out some longer snippet of code that takes much longer to compute so the overhead is not a significant part of the total time. When I do it in MATLAB I get this on my old, slow computer:
Hello, World!
Elapsed time is 0.000162 seconds.
>>
To format your code as code, you highlight the code with the mouse and then click the Code icon on the Answers edit box tool ribbon. Pretty simple.

11 Comments

@the cyclist thanks for clarifying. I have Windows. I still think most of the time is taken up not by disp() but by the overhead of launching MATLAB as a program with no GUI.
Sorry I deleted the comment that @Image Analyst is replying to, because upon further reflection I felt that it was unnecessary.
The gist was that I assume @Matthew Elmer was launching that command from a Mac terminal, not the MATLAB command line.
  1. My use case doesn't allow for use of the MATLAB REPL.
  2. Please show me how to use this button for general, non-MATLAB code:
> the overhead of launching MATLAB as a program with no GUI.
If anything, launching MATLAB without the GUI should be faster, not slower. I passed all of the options that could possibly help and yet I'm still staring at my terminal for two and a half seconds waiting for it to print "Hello, World!"
That's not the point. Perhaps launching MATLAB with no GUI is faster than without a GUI. But who cares? When running a large program, as opposed to s single line, you don't care about the overhead to launch the program - that overhead should not be part of the benchmark timing. The point I'm making is that using a single line of code to display a single line of text is not a valid benchmark to compare the speed of MATLAB with Python because your benchmark code is such a small part of the total time, which includes the overhead of the Operating System launching the main program. Heck, even with MATLAB running, and (say) Jupyter Notebook running, so there is no overhead of launching the main program, using a single line of code to compare speeds of various languages is not a valid comparison. Here is one comparison that shows MATLAB is faster:
MATLAB Matrix Multiplication Performance: 5x Faster Than NumPy
In my opinion, if you have a bunch of independent tasks to accomplish, it is valid to ask "How long does it take to get them all done?" . Startup time plus computation time counts.
If you are in a situation where MATLAB needs to be started a lot, then it is probably time to consider using MATLAB Production Server
@Image Analyst is essentially saying that only throughput ever matters and that you can forget about latency in all cases, for all programs, for all problem domains, every time. I don't even have to address such a ridiculous claim, because you can already guess what the response might be.
People like @Image Analyst are why it takes 30 seconds to spool up Microsoft Word, MATLAB, Discord and other Electron apps, etc. I'm sick of modern software being 100x - 1000x slower than it needs to be and having mile-long excuse trains that keep it that way.
If there's a problem with how long it takes to launch the program, maybe fix it? Clearly Python wastes no time at all in starting its interpreter.
Hilariously, @Image Analyst had to go digging for some article that someone else (likely ChatGPT) wrote about an entirely unrelated performance comparison to have any sort of point to bring to the discussion. Unfortunately, I'm not trying to do a matrix multiplication here. I'm just trying to start MATLAB in a reasonable timeframe. And by the way, that article is embarrasing. It doesn't even cite the benchmark that supposedly reveals how blazingly fast MATLAB is! It also naively touts the power of MATLAB's multithreading "capabilities," despite the fact that MATLAB's parallel "toolbox" is widely recognized to be near worthless on anything with more than 3 CPU cores. This part of the article got a chuckle from me:
"MATLAB uses highly optimized libraries like Intel’s Math Kernel Library (MKL) and BLAS (Basic Linear Algebra Subprograms) for its matrix operations. These libraries are written in low-level languages like C and Fortran, which are known for their speed and efficiency.
NumPy also uses BLAS and LAPACK (Linear Algebra Package) for matrix operations..."
I'm not sure what point they're trying to make here, but they didn't do so well, lol.
@Image Analyst still has not shown me how to post non-MATLAB code snippets, by the way, even though he claims it's "Pretty simple."
@Walter Roberson my application will not be licensing any additional MathWorks products. It will only make use of what's already on the machine for users that can't be expected to use/learn a better language.
@Matthew Elmer One reason I really like getting and giving help on MATLAB answers is it is generally a very friendly site. I realize that sometimes passion and enthusiasm for a topic may mistakenly be taken for sounding angry, so if I am misreading your tone please forgive me. But, if not, if you can try to keep it friendly and constructive I would appreciate it. Thanks
My apologies if my tone came across as angry. I really would like to come across as friendly, but I cannot compromise on calling people out on responses that are actively counterproductive to users with time/resource constraints and the computer programming industry at large. The benchmarks that I shared show that MATLAB could be a lot faster on headless startup and thus a lot more valuable to more users. If I have to contend with an avalanche of excuses, especially ones like this that don't match the friendly tone you're requesting either, I'm going to have to compromise on tone a bit for the sake of clarity.
Your criticism is well taken, though, and I'll try even harder to keep the atmosphere polite.
Thanks Matthew, I very much appreciated your thoughtful response regarding keeping it friendly.

Sign in to comment.

I'm not sure how you are running your test, running this script inside this online environment seems to indicate it is very fast compared to what you report
tic
disp('Hello World!')
Hello World!
toc
Elapsed time is 0.015690 seconds.
When I just type on the command line on my laptop, it is even faster
tic,disp('Hello World'),toc
Hello World
Elapsed time is 0.000805 seconds.

1 Comment

My timing was done in a Bash terminal. Try running the Python command or compiling a C program and you'll see that it's not the same as MATLAB's REPL.

Sign in to comment.

To me, this all seems to be making a mountain out of a mole hill.
Yes, if you are going to launch MATLAB, even with no gui interface, MATLAB will surely cache all the functions it uses. It will do lots of crapola that you don't care about, IF your only goal is to display a line of text, and then quit. If that is what you will do on your computer, then you need ot be using a different tool, not MATLAB. That Python (or C) is faster to display a line of text, good for Python. Use it instead.
In your case, it appears that you want to use MATLAB as you are trying to use it, AND that the overhead of booting MATLAB every time is high. If you compare any of those anguages, they all have their advantages, and disadvantages. As @Image Analyst points out, for at least some operations MATLAB is faster than Python. (I can also point out one specific case that I know of where Python wins the battle by a mile. But I also have a workaround in MATLAB.)
I'm sorry, but no language is perfect. They all live under their own sets of fundamental assumptions that influence what they will do well.

1 Comment

It's not my choice to use MATLAB. I'm merely accomodating those who don't have the time to learn something better. After seeing how much time they spend sitting around, no wonder they don't have any left for learning a better language!

Sign in to comment.

Categories

Products

Release

R2022b

Asked:

on 6 Sep 2023

Edited:

Jon
on 15 Sep 2023

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!