need to timestamp to ms resolution AND be able to codegen it to C++

datetime command is doing what i need (provides time resolution to ms) BUT its not allowed by codegen. Is there equivalent command that does codegen? datetime('now','TimeZone','local','Format','d-MMM-y HH:mm:ss:ssssss Z'); Alternatively, datetime('now') codegens BUT need resolution to ms.

 Accepted Answer

Hi
While you can't directly use the full formatting and timezone features of the "datetime" function in a codegen context, you can still capture high-resolution time. One approach is to use basic "datetime" functionality that is supported by codegen and then manually manipulate or format the output as needed.
Here's the workaround:
  • Create your own datetime function which outputs the milli seconds by manipulating the original "datetime" output
function [year , month, day, hour, minute, second,ms] = myDatetime()
currentTime = datetime('now');
year = currentTime.Year;
month = currentTime.Month;
day = currentTime.Day;
hour = currentTime.Hour;
minute = currentTime.Minute;
second = currentTime.Second;
integ=floor(second);
ms=floor((second-integ)*1000); % Note sometimes you may loose precision here when number of decimals are greater the 4
end
  • Replace the builit-in "datetime" function with your function "myDatetime" in your code and regenerate your C/C++ code.

2 Comments

Thank you. This converts to C++ but there is a resolution issue. When event happens I put a timestamp. In Matlab i see 6 numbers after decimal. But when codegen runs it there are only 3 digits after decimal. I realized hat i do need more than ms resolution. Is there a way to increase both MAtlab and C++ resolution?
In Matlab:
Date: 2024- 4-10 Time: 8:46:54.013099
Date: 2024- 4-10 Time: 8:46:54.024811
Date: 2024- 4-10 Time: 8:46:54.036219
In C++
Date: 2024- 4-10 Time: 8:48:43.122000
Date: 2024- 4-10 Time: 8:48:43.127000
Date: 2024- 4-10 Time: 8:48:43.132000
just fyi, i am doing this...
T = datetime('now');
fprintf('Date: %4.0f-%2.0f-%2.0f Time: %2.0f:%2.0f:%9.6f ', T.Year, T.Month, T.Day, T.Hour, T.Minute, T.Second);
fprintf('\n');

Sign in to comment.

More Answers (0)

Categories

Find more on Operators and Elementary Operations in Help Center and File Exchange

Products

Release

R2022b

Asked:

on 9 Apr 2024

Commented:

on 10 Apr 2024

Community Treasure Hunt

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

Start Hunting!