所以我知道如何以秒为单位打印自纪元以来的时间,显然甚至以毫秒为单位,但是当我尝试以纳秒为单位时,我总是得到一个太小的整数的虚假输出,并且它有时打印的数字小于上次运行的数字。
#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;
}
例如,从这个运行中我得到了自纪元以来的 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;
}
关于c - 自纪元以来的打印时间(以纳秒为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54763262/