How to get Matlab timestamp in whole seconds

I need to get a timestamp in whole seconds that won't flip. This can be elapsed CPU seconds, or elapsed hours or seconds in seconds.

'clock' gives a vector of date / time in years ... seconds. But I can't figure out how to convert this to whole seconds.

cputime returns the elapsed integer number of seconds, but "This number may overflow the internal representation and wrap around."

+3


source to share


1 answer


How about round(3600 * 24 * now)

?

According to the manual , it now

returns the number of days since year 0 as a floating point number. So multiplying by 86400 should give seconds.

It is usually best to use a fixed point format for keeping track of time, but since you are only interested in whole seconds, this shouldn't be too much of a problem. Temporary resolution now

due to floating point resolution can be found as follows:

>>  eps(now*86400)
ans =
   7.6294e-06

      



Or almost 8 microseconds. This should be good enough for your use case. Since these are 64 bit floating point numbers, you won't have to worry about wrapping for your lifetime.

One of the practical problems is that the number of seconds since year 0 is too large to be printed as an integer in the Matlab prompt with standard settings. If it bothers you, you can do fprintf('%i\n', round(3600 * 24 * now))

or just subtract an arbitrary number for example. to get the number of seconds since 2000 you can do

epoch = datenum(2000, 1, 1);
round(86400 * (now - epoch))

      

which is currently printing 488406681

.

+2


source







All Articles