this post was submitted on 15 Jun 2023
6 points (100.0% liked)
Programming
568 readers
1 users here now
All things programming and coding related. Subcommunity of Technology.
This community's icon was made by Aaron Schneider, under the CC-BY-NC-SA 4.0 license.
founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
This is correct, however it is important to note that the C standard allows arbitrary values at the beginning of the program. The manpage does a better job explaining it.
Doing a bit of research, it looks like the POSIX
time_t time(time_t *dest)
function (man) is available on Windows (see here). So I would recommend that overclock_t clock(void)
as it will operate more consistently across platforms.The arbitrary values at the beginning of the program is the reason you want to measure a difference rather than an absolute time. Like you don't want to simply go
(double)clock() / CLOCKS_PER_SEC
at the end of the program. That would only work if you knew for certain that the clock started at 0 on program launch. Some operating systems may ensure this. Others may only zero it when the CPU is booted, for example. So it's just not safe to work with absolute times, but differences between time stamps should still behave consistently across platforms.Now, the problem with
time()
and friends is they represent the kind of time displayed by your computer. In most cases, this should work fine, but occasionally, the OS may adjust this time for a number of reasons. It may be jumping ahead or back due to daylight savings, for example, or adding/losing some seconds as it syncs the computer clock to an NTP server someplace. What you want to use to avoid such shenanigans in measuring time elapsed is a steady clock which ticks along regardless of what the OS decides to do. I thinkclock()
is your best bet for that in plain C? (It also may have a higher resolution thantime()
, though that's not super important if you're only worried about counting hours.)