Get UTC Time in Generated Code

30 次查看(过去 30 天)
Michael
Michael 2023-8-14
I need to get UTC time down to miliseconds at least (i.e. 1692039433503685.321 seconds) in a piece of generated code C++ code. Unfortunately, Coder doesn't support the 'TimeZone' inputs in datetime, otherwise I'd just use posixtime( datetime('now','TimeZone','UTC') ).
I tried using coder.ceval to call the fuctions in the chono C++ library, but the UTC clock there is only available in the C++20 language standard and Matlab only supports up to C++11.
Is there a good way of doing this?
  4 个评论
Rik
Rik 2023-8-15
There is a UTC in C. Can you use that?
My getUTC function doesn't support code generation, but it does include this C function:
utc_time_c={'#include "mex.h"';
'#include "time.h"';
'';
'/* Abraham Cohn, 3/17/2005 */';
'/* Philips Medical Systems */';
'';
'void mexFunction(int nlhs, mxArray *plhs[], int nrhs,';
' const mxArray *prhs[])';
'{';
' time_t utc;';
' ';
' if (nlhs > 1) {';
' mexErrMsgTxt("Too many output arguments");';
' }';
' ';
' /* Here is a nice ref: www.cplusplus.com/ref/ctime/time.html */';
' time(&utc);';
' /* mexPrintf("UTC time in local zone: %s",ctime(&utc)); */';
' /* mexPrintf("UTC time in GMT: %s",asctime(gmtime(&utc))); */';
' ';
' /* Create matrix for the return argument. */';
' plhs[0] = mxCreateDoubleScalar((double)utc);';
' ';
'}'};
Denis Gurchenkov
Denis Gurchenkov 2023-9-18
Hi Mike, I don't have an answer to the main questipn you have, but one possible avenue for progress is to use the C++ 20 functions.
You said that "MATLAB Coder only supports up to C++11" - that is not quite correct. Coder-generated code should work just fine with C++20. The page you referred to just says "coder does not know how to use the C++20 features - at most, it'll generate code using C++11 features". But since C++ standards are generally forward compatible, you should be able to just set the language flag for the C++ compiler. If you add the following line to your matlab function:
coder.updateBuildInfo('addCompileFlags','/std:c++20');
and generate code using "codegen ... -lang:C++" then you should /std:c++20 added to the c compiler command line.

请先登录,再进行评论。

回答(1 个)

Corey Silva
Corey Silva 2023-9-19
Hi Michael,
You should be all set to use posixtime here with an unzoned datetime.
From the posixtime help text:
"If T is unzoned, then POSIXTIME treats T as though its time zone is UTC, and not your local time zone."
This means that posixtime(datetime('now','TimeZone','UTC')) and posixtime(datetime('now')) have the same output.

类别

Help CenterFile Exchange 中查找有关 MATLAB Coder 的更多信息

产品


版本

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by