在Matlab中,我需要执行计算。 我可以通过两种方法进行此计算,但我不知道先验哪种方法会更容易。 一种方法需要计算机一毫秒才能完成,另一种方法需要几分钟。 所以我需要一种方法来询问Matlab在一行代码上停留了多长时间。 像这样的东西:
start timer
run this line of code
if 0.1 second has passed
stop and run this line of code
end
这可能吗?
请注意,这个问题https://stackoverflow.com/questions/21925137/how-can-i-abort-program-execution-in-matlab不相关,因为我不想真正停止程序。
您将必须使用一些线程/进程管理例程。大致如下:
% 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