I am working with some python codes that call a Matlab function. The Matlab function takes a 3D array as input and the size is about 87*195*126. I modified the mlarray_sequence.py
as suggested in this post. The time spent on converting to Matlab double array does significantly reduce (~0.4 sec). However, it still seems that it takes about 10 seconds to pass the array to the Matlab function, as can be seen by timing each step as follows:
import numpy as np
import matlab.engine
import matlab
from io import StringIO
from os.path import abspath, dirname, join
import timeit
def test1():
start_time = timeit.default_timer()
matlabEngine = matlab.engine.connect_matlab()
directory = abspath(dirname(__file__))
matlabFolder = directory
matlabEngine.addpath(matlabFolder)
matlabEngine.cd(matlabFolder)
timepoint = timeit.default_timer()
print('Elapsed time for connecting matlab is {} sec'.format(timepoint - start_time))
img = np.random.rand(87, 195, 126)
timepoint1 = timeit.default_timer()
imgMatlab = matlab.double(img)
timepoint2 = timeit.default_timer()
print('Elapsed time for creating matlab array is {} sec'.format(timepoint2 - timepoint1))
out = StringIO()
err = StringIO()
matlabEngine.test2(imgMatlab, stdout=out, stderr=err)
print(out.getvalue())
print(err.getvalue())
timepoint3 = timeit.default_timer()
print('Elapsed time for matlab script is {} sec'.format(timepoint3 - timepoint2))
test1()
function result = test2(img)
tic
result = 1;
toc
And the output is:
Elapsed time for connecting matlab is 0.0893801 sec
Elapsed time for creating matlab array is 0.40231419999999996 sec
Elapsed time is 0.000603 seconds.
Elapsed time for matlab script is 10.4323424 sec
[Done] exited with code=0 in 11.491 seconds
So is there any way to reduce the time spent on passing the array to matlab function?
P.S.: I have already shared the matlab session by typing matlab.engine.shareEngine
before I run the script.