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.

 Accepted Answer

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 Comments

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.

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Products

Release

R2022a

Asked:

on 10 Feb 2025

Commented:

on 10 Feb 2025

Community Treasure Hunt

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

Start Hunting!