4
votes

I need to get a timestamp in integer seconds, that won't roll over. Can be elapsed CPU seconds, or elapsed clock or epoch seconds.

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

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

1

1 Answers

3
votes

What about round(3600 * 24 * now)?

According to the manual, now returns the number of days since the year 0, as a floating point number. Multiplying by 86400 should thus give seconds.

Usually it is better to use a fixed-point format for keeping track of time, but since you are only interested in integer seconds, it should not be too much of a problem. The time resolution of now due to floating point resolution can be found like this:

>>  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 should not have to worry about wrapping around within your lifetime.

One practical issue is that the number of seconds since the year 0 is too large to be printed as an integer on the Matlab prompt with standard settings. If that bothers you, you can do fprintf('%i\n', round(3600 * 24 * now)), or simply subtract some arbitrary number, e.g. to get the number of seconds since the year 2000 you could do

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

which currently prints 488406681.