Is there a way to subtract/sum the elapsed time in

2019-09-01 19:14发布

问题:

Say we have a call-back timer function call_time(obj, event). I want to know the elapsed time (delt_time) during the execution of timer function once it is started. Furthermore, I want to use that elapsed time to decide if the function will be continued executing or be terminated (say delt_time > 60s). I want the timer function to determine the running time concurrently. By doing this way, the code knows when to terminate the program once it reaches to the threshold. Actually, I have asked a couple of similar questions on the basis of different ways that I have tried. But no answers yet.

Now I've tried

     function call_time(obj, event)
         event_time = event.Data.time;
         event_time = event.Data.time - event_time;
         while event_time < 60
             %execute commands
         end
         if event_time > 60
             %terminate execution
         end
     end

But it does not work.Below is how I call the timer function.

     TimerHandle = timer;
     TimerHandle.StartFcn = @(~,thisEvent)disp([thisEvent.Type ' executed '...
         datestr(thisEvent.Data.time,'dd-mmm-yyyy HH:MM:SS.FFF')]);
     TimerHandle.TimerFcn = @call_time;
     TimerHandle.StopFcn = @TimerCleanup;
     TimerHandle.period = 10;
     TimerHandle.ExecutionMode = 'fixedRate';
     start(TimerHandle);

I also tried the way that Tom suggested. But not working as well.

     function call_time(obj, event)
         event_time = event.Data.time;
         delta_time = event.Data.time - event_time;
         while delta_time < 60
             %execute commands
             delta_time = event.Data.time - event_time;
             fprintf('Elapsed %.2f sec\n', delta_time);
         end
         if delta_time > 60
             %terminate execution
         end
     end

回答1:

Assuming you want to track time since the callback entrance, you can use tic/toc:

function call_time(obj, event)
    elapsed_sec = 0;
    t = tic();
    while elapsed_sec < 60
        % execute commands, e.g. something time-consuming
        A = randn(10000);
        elapsed_sec = toc(t);
        fprintf('Elapsed %.2f sec\n', elapsed_sec);
    end
end

UPDATE on concurrency - Matlab execution is single-threaded, so nothing like this exists out of the box. You could spawn java treads and have one terminate another, but you would obviously not be able to run Matlab code inside (not easily, at least).

For a pure java solution, you can check out this question. If you really-really need to terminate Matlab code, you can use aforementioned Java solution, and call back from Java to Matlab via JMI / MatlabControl or MATLAB Engine API for Java (I am actually not even certain the thread would be terminated in this case). Even if it does work, this is unnecessarily more complicated than simply adding a bunch of toc checks between your statements.