In Matlab, I need to perform a calculation. There are two ways I can do this calculation, but I don't know a priori which one will be easier. One way will take the computer a millisecond to finish, and the other will take minutes. So I need a way to ask Matlab how long it's been stuck on one line of code. Something like this:
start timer
run this line of code
if 0.1 second has passed
stop and run this line of code
end
Is this possible?
Note that this question https://stackoverflow.com/questions/21925137/how-can-i-abort-program-execution-in-matlab is not relevant because I don't want to actually stop the program.
You could take advantage of some thread/process management routines. Something along the lines of:
% Create a thread pool
pool = parpool('Threads');
% Submit the tasks to the thread pool
future1 = parfeval(pool, @countToN, 0, 10);
future2 = parfeval(pool, @countToN, 0, 1000);
% Periodically check if any of the threads have finished
while ~strcmp(future1.State,'finished') && ~strcmp(future2.State,'finished')
pause(0.1); % Check every 100ms
disp("checking stats")
if strcmp(future1.State,'finished')
fprintf('Task 1 finished, cancelling Task 2.\n');
future2.cancel();
elseif strcmp(future2.State,'finished')
fprintf('Task 2 finished, cancelling Task 1.\n');
future1.cancel();
end
end
% Wait for both tasks to finish (in case they were cancelled)
wait([future1, future2]);
% Clean up the thread pool
delete(pool);
function countToN(n)
for i = 1:n
fprintf('Counting to %d: %d\n', n, i);
pause(0.1); % 10ms delay
end
end