MATLAB Answers

1

Performance of system/dos function

Asked by Xiangrui Li on 3 May 2017
Latest activity Commented on by Xiangrui Li on 17 May 2018
[status, cmdout] = system(cmd)
has been reported to be slow for a while (see this and this), but there seems no satisfying solution yet.
Here is what I tested for Windows command reg.exe, trying to figure out a workaround.
cmd = 'reg.exe query HKEY_LOCAL_MACHINE\HARDWARE /s'; % as an example
tic; [status, cmdout] = system(cmd); toc
Elapsed time is 3.517736 seconds.
whos cmdout
Name Size Bytes Class Attributes
cmdout 1x95249 190498 char
tic; [status, cmdout] = dos(cmd); toc
Elapsed time is 3.512847 seconds.
tic; cmdout = evalc(['! ' cmd]); toc
Elapsed time is 3.509961 seconds.
As we can see, system(), dos() and evalc('!') have similar performance. When I test the same cmd in other programs (Octave and python), it takes about 0.6 to 0.7 seconds. Running it at Windows command prompt takes less than a second based on my eye test. Then I tried to redirect output to a file:
tic; [status, cmdout] = system([cmd ' >myFile']); toc
Elapsed time is 0.886915 seconds.
This improves the performance significantly. The cmdout is empty now as expected.
Does this suggest there should be a way to improve system() for dealing with cmdout?
Is there a way to redirect cmdout to a Matlab string, so we can avoid to read and delete the temp file?

  6 Comments

Just found jsystem at Github based on java. It can be super fast. For example, for the FTDI example:
ftdi = 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\FTDIBUS';
cmd = ['reg.exe query ' ftdi ' /s'];
tic; [err, str] = jsystem(cmd, 'noshell'); toc
Elapsed time is 0.045354 seconds.
With system():
tic; [err, str] = system(['reg.exe query ' ftdi ' /s']); toc
Elapsed time is 1.438463 seconds.
The time is 1.44 vs 0.045 seconds! However, with the HARDWARE example:
cmd = 'reg.exe query HKEY_LOCAL_MACHINE\HARDWARE /s';
tic; [err, str] = jsystem(cmd); toc % this won't work
This hangs Matlab with or without 'noshell' option. I have no idea why this happens.
raym
on 3 Apr 2018
I encountered similar problems and finally got the reason, but not solution.
When matlab runs dos('command'), the thread was diverted to the dos command and wait it to finish. e.g., if ping www.baidu.com takes 10 s, the tic toc will take more than 10s. During this time, the command window is not responsive. One solution is add a "&" at the end. this will get thread back to command window immediately. A drawback is that it will failed to return the output of command, i.e, you lost monitoring of your command and do not know when it finishes.
The jsystem at Github has fixed the hanging problem.

Sign in to comment.

0 Answers