How to format time with fprintf

45 vues (au cours des 30 derniers jours)
JDA
JDA le 28 Fév 2022
Commenté : Star Strider le 1 Mar 2022
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?

Réponse acceptée

Star Strider
Star Strider le 28 Fév 2022
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 commentaires
JDA
JDA le 1 Mar 2022
Great answer! That solved my problem. Thanks.
Star Strider
Star Strider le 1 Mar 2022
Thank you!
As always, my pleasure!

Connectez-vous pour commenter.

Plus de réponses (1)

Walter Roberson
Walter Roberson le 28 Fév 2022
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

Catégories

En savoir plus sur Time Series Objects dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by