简体   繁体   中英

How to get current timestamp in nanoseconds in linux using c

I know we can use clock_gettime(CLOCK_MONOTONIC) .

Question i try asking is that if i need the time in nanoseconds say from epoch, it would be a huge number.

For example:

  • Seconds since epoch is 13438461673 so 13438461673 * 1000000000

How do i fit it inside a 64bit integer?

CLOCK_MONOTONIC is from arbitrary epoch, and it actually varies from machine to machine and every boot in Linux. You should use it only to measure intervals , ie

  (int64_t)(after.tv_sec - before.tv_sec) * (int64_t)1000000000UL
+ (int64_t)(after.tv_nsec - before.tv_nsec)

. For timestamps, use CLOCK_REALTIME , as it uses the 1970-01-01 00:00:00 UTC epoch. int64_t can handle CLOCK_REALTIME timestamps at nanosecond precision –

(int64_t)(t.tv_sec) * (int64_t)1000000000 + (int64_t)(t.tv_nsec)

–, dates from year 1679 to 2261 at least; the range is ±292 years, not ±145 years.

– Nominal Animal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM