How to format time with fprintf

45 次查看(过去 30 天)
To get the time it takes a program to execute, I set date_1 = datetime('now") at the beginning of a program, and date_2 = datetime('now) at the end of the program. Then Elapsed_time = date_2 - date_1. I would like to print the elapsed time using the fprintf command, and I would like it to be formatted to show minutes and seconds. How do I do that? Could you provide an example?

采纳的回答

Star Strider
Star Strider 2022-2-28
Try this —
date_1 = datetime('now');
for k = 1:1E+8
rand;
end
date_2 = datetime('now');
Elapsed_time = date_2 - date_1;
Elapsed_time.Format = 'mm:ss.SSS';
fprintf('Elapsed time = %s', Elapsed_time)
Elapsed time = 00:07.641
I added the milliseconds simply for the demonstration.
.
  4 个评论
JDA
JDA 2022-3-1
Great answer! That solved my problem. Thanks.
Star Strider
Star Strider 2022-3-1
Thank you!
As always, my pleasure!

请先登录,再进行评论。

更多回答(1 个)

Walter Roberson
Walter Roberson 2022-2-28
date_2 = datetime('now');
date_1 = date_2 - rand()^2 %days
date_1 = datetime
28-Feb-2022 14:32:31
Elapsed_time = date_2 - date_1
Elapsed_time = duration
05:51:40
Elapsed_time.Format = 'mm:ss'
Elapsed_time = duration
351:40
fprintf('elapsed time was: %s\n', Elapsed_time)
elapsed time was: 351:40

类别

Help CenterFile Exchange 中查找有关 Time Series Objects 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by