For statement - print on exactly 1 second

24 ビュー (過去 30 日間)
Dejan Hrovatin
Dejan Hrovatin 2017 年 2 月 11 日
コメント済み: Dejan Hrovatin 2017 年 3 月 5 日
Hi!
I want to print some text (ex. test) 20 times, every 1 second. I tried with for statement:
close all;
clear all;
tic
for i=1:20
toc
disp('test');
pause(i-toc);
end
If I run this code, I see that time drifts also for 20 ms from whole second (I know that It depends on many things, occupancy of CPU is for ex. one thing). Is any other option to come closer to the whole second?
Thank you! Best regards, Dejan

採用された回答

Jan
Jan 2017 年 2 月 11 日
編集済み: Jan 2017 年 2 月 11 日
java.lang.Thread.sleep(t*1000) than is more accurate than pause(t)
tic;
for i=1:20
toc
disp('test');
java.lang.Thread.sleep((i-toc)*1000);
end
["test" removed for compactness]
Elapsed time is 0.008428 seconds.
Elapsed time is 1.000497 seconds.
Elapsed time is 1.999536 seconds.
Elapsed time is 2.999586 seconds.
Elapsed time is 4.000012 seconds.
Elapsed time is 4.999816 seconds.
Elapsed time is 5.999633 seconds.
Elapsed time is 6.999679 seconds.
Elapsed time is 7.999731 seconds.
Elapsed time is 8.999758 seconds.
Elapsed time is 9.999807 seconds.
Elapsed time is 10.999854 seconds.
Elapsed time is 11.999904 seconds.
Elapsed time is 12.999952 seconds.
Elapsed time is 13.998999 seconds.
Elapsed time is 14.999047 seconds.
Elapsed time is 15.999100 seconds.
Elapsed time is 16.999148 seconds.
Elapsed time is 17.999193 seconds.
Elapsed time is 18.999260 seconds.
See http://undocumentedmatlab.com/blog/pause-for-the-better . But my measurements with pause look fairly accurate also.
Use a timer for triggering code after certain times.
  1 件のコメント
Dejan Hrovatin
Dejan Hrovatin 2017 年 3 月 5 日
Jan Simon, thank you! This is exactly what I was looking for.

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

その他の回答 (2 件)

Image Analyst
Image Analyst 2017 年 2 月 11 日
Instead of pause(i-toc), use pause(1). Your way did not pause exactly 1 second every time - the time changed upon each iteration.
  1 件のコメント
Image Analyst
Image Analyst 2017 年 2 月 11 日
If the time to complete each iteration changes, then you can use while and toc:
for i = 1 : 20
startTime = tic;
% Lengthy and variable code...
% Wait until 1 second has passed
elapsedTime = toc(startTime); % In seconds
while elapsedTime < 1
elapsedTime = toc(startTime); % In seconds
end
end

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


Dejan Hrovatin
Dejan Hrovatin 2017 年 2 月 11 日
編集済み: Dejan Hrovatin 2017 年 2 月 11 日
I wrote pause(i-toc) because eventually I will have to do some another operations in the same loop. Each operation need some time, and if then I use pause(1), I think that I will make bigger "error", because the time taken by each operation is not always the same. Recently I found timer function in MATLAB (doc timer). I will try this.

カテゴリ

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