我正在编写一个输出到控制设备的 DAQ 的代码。我想让它每 1 秒精确地发送一次信号。根据处理器的性能,代码有时需要长于或短于 1 秒。有什么办法可以改进这段代码吗? 已用时间为 1.000877 秒。 已用时间为 0.992847 秒。 已用时间为 0.996886 秒。
for i= 1:100
tic
pause(.99)
toc
end
最佳答案
已知使用 pause
相当不精确(大约 10 毫秒)。 Matlab 在最新版本中优化了 tic toc
,使其开销较低且尽可能精确(请参阅 here)。
您可以使用 tic toc
比使用以下代码暂停更精确:
ntimes = 100;
times = zeros(ntimes,1);
time_dur = 0.99;
for i= 1:ntimes
outer = tic;
while toc(outer) < time_dur
end
times(i) = toc(outer);
end
mean(times)
std(times)
这是我 50 次测量的结果:mean = 0.9900
,std = 1.0503e-5
,这比使用暂停要精确得多。
使用原始代码,只需暂停,进行 50 次测量,我得到:mean = 0.9981
,std = 0.0037
。
关于performance - 使用 Tic Toc 控制循环速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23918943/