Calculate time for count

7 ビュー (過去 30 日間)
m
m 2016 年 1 月 28 日
コメント済み: Guillaume 2016 年 1 月 28 日
i have a sequence of iteration i.e
seconds=5;
for i=0:seconds/100:seconds
% run task
end
how can i match 5 equal to 5 seconds? i do know 5 here is not exactly 5 seconds. is it depends on the processor speed? different computer, different time count?
so, next time if i want the calculation to be faster i just change 5 into 2 or 1.
thank you.

回答 (2 件)

Guillaume
Guillaume 2016 年 1 月 28 日
編集済み: Guillaume 2016 年 1 月 28 日
While theoretically, you could pace your loop to run at whichever speed you want by using tic, toc and pause, this wouldn't be very efficient and prone to drifting.
A better way of running a task at regular interval is to use a timer:
task = @(~,~) disp('event');
t = timer('Period', 5, 'ExecutionMode', 'fixedRate', 'TaskToExecute', 100, 'TimerFcn', task)
t.Run;
Your task must of course take less time to execute than the period of the timer. If not, you can set the 'BusyMode' property of the timer to decide what happens.
  2 件のコメント
m
m 2016 年 1 月 28 日
編集済み: Jan 2016 年 1 月 28 日
is there any easy way?
i've tried now
i.e
t1=now;
t2=now;
elapsed_days1 = t2 - t1;
elasped_second1 = elapsed_days1 *24*60*60;
% elapsed_seconds1
but, it only return total time the task is running not the time i control.
[EDITED, Jan, Code formatted]
Guillaume
Guillaume 2016 年 1 月 28 日
It's only three lines of code to use a timer, you don't get any easier! timer is the easy way and more importantly is the reliable way. And it's designed for the purpose of running tasks at regular intervals.
As I said you can also regulate the pace of a loop with tic, toc, pause or some java thread sleep (see Jan's answer). I don't find that any easier, and I can guarantee you that after a while your period will have drifted slightly. It's also harder to monitor for task overrun.

サインインしてコメントする。


Jan
Jan 2016 年 1 月 28 日
編集済み: Jan 2016 年 1 月 28 日
Guillaume's suggestion is the most accurate and direct solution: Use a timer if you need a time event.
Another approach:
delay = 5; % In seconds
for k = 1:100
tic
% You computations here
disp(datestr(now, 0));
pause(delay - toc);
end
Note: This is more accurate than pause:
java.lang.Thread.sleep(delay * 1000);

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by