Is it better to use tic/toc or a timer function for tracking time?

I am using MATLAB App Designer to make a GUI to read data coming in from an arduino. I want to assign timestamps to incoming data to use for graphing it live, and I am wondering whether it is better to use a timer function or tic/toc? I am mostly asking for performance reasons, it's a rather complex application and I don't want to add any more execution time or whatnot that I can avoid.

 采纳的回答

If you want to retrieve the current time, use:
dt = datetime('now')
dt = datetime
10-Feb-2025 16:32:03
To retrieve it as text data:
s = string(dt)
s = "10-Feb-2025 16:32:03"
Depending on how you want the time represented (Different time zone? Different display format?) you may need to add other options from the datetime documentation page.
dt = datetime('now', TimeZone="America/New_York")
dt = datetime
10-Feb-2025 11:32:03
dt = datetime('now', Format="dd/MM/yy hh:mm:ss a")
dt = datetime
10/02/25 04:32:03 PM
The tic and toc functions are for measuring elapsed time, and timer schedules when commands should be executed.

3 个评论

Great, thanks. I do want to store the actual date/time and write it to a text file for each line of data, so datetime will work for that. For graphing I want to use the elapsed time since the start of the test, so it sounds like tic/toc will work for that, which is what chatGPT initially suggested, but I wanted to confirm. Thanks!
Note that elapsed time can be found by taking the difference of two datetimes, which is a duration (which is suitable for graphing/plotting).
t_start = datetime('now')
t_start = datetime
10-Feb-2025 17:14:50
pause(3)
t_now = datetime('now')
t_now = datetime
10-Feb-2025 17:14:53
delta_t = t_now - t_start
delta_t = duration
00:00:03
And you can convert a duration into a number by calling the seconds, minutes, or hours functions.
t_start = datetime('today')
t_start = datetime
10-Feb-2025
t_now = datetime('now')
t_now = datetime
10-Feb-2025 18:11:58
delta_t = t_now - t_start
delta_t = duration
18:11:58
fprintf("It is now %g seconds or %g minutes or %g hours since midnight.", ...
seconds(delta_t), minutes(delta_t), hours(delta_t))
It is now 65518.7 seconds or 1091.98 minutes or 18.1996 hours since midnight.
Or if you want to split it into components, use the hms function.
[h, m, s] = hms(delta_t);
fprintf("It has been %d hours, %d minutes, and %g seconds since midnight.", ...
h, m, s)
It has been 18 hours, 11 minutes, and 58.6646 seconds since midnight.

请先登录,再进行评论。

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 MATLAB 的更多信息

产品

版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by