因此,我知道如何打印自纪元以来的时间,以秒为单位,甚至以毫秒为单位,但是当我尝试以纳秒为单位时,我一直在虚假输出一个太小的整数,有时它打印的数字小于上一次运行的数字。
#include <stdio.h>
#include <time.h>
int main (void)
{
long int ns;
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
ns = spec.tv_nsec;;
printf("Current time: %ld nonoseconds since the Epoch\n", ns);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
例如,从这个时间开始我得到了35071471纳秒。
任何帮助使此正确显示将不胜感激。
纳秒部分只是“小数”部分,您也必须添加秒。
// otherwise gcc with option -std=c11 complaints
#define _POSIX_C_SOURCE 199309L
#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <inttypes.h>
#define BILLION 1000000000L
int main(void)
{
long int ns;
uint64_t all;
time_t sec;
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
sec = spec.tv_sec;
ns = spec.tv_nsec;
all = (uint64_t) sec * BILLION + (uint64_t) ns;
printf("Current time: %" PRIu64 " nanoseconds since the Epoch\n", all);
return 0;
}
Run Code Online (Sandbox Code Playgroud)