gpt4 book ai didi

clock_gettime API 给出负值

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:42:25 26 4
gpt4 key购买 nike

我想要以微秒为单位的当前系统时间,所以我使用 clock_gettime 编写了一个程序,但它有时会返回负值。有人可以帮我解决这个问题吗?

int main(void) {
struct timespec tms;

/* The C11 way */
/* if (! timespec_get(&tms, TIME_UTC)) { */

/* POSIX.1-2008 way */
if (clock_gettime(CLOCK_REALTIME,&tms)) {
return -1;
}
/* seconds, multiplied with 1 million */
long long micros = tms.tv_sec * 1000000;
/* Add full microseconds */
micros += tms.tv_nsec/1000;

printf("Microseconds: %lld\n",micros);
return 0;
}

最佳答案

希望下面的代码对你有帮助:

    #include<stdio.h>
#include<math.h>
#include<time.h>

void get_time_in_ms()
{
long ms;
time_t time;
struct timespec spec;
char tm[14];

clock_gettime(CLOCK_REALTIME, &spec);

time = spec.tv_sec;
ms = round(spec.tv_nsec / 1000000 ); // Convert nanoseconds to milliseconds

printf("Current time: %lu.%03ld seconds since the Epoch\n", time, ms);
sprintf(tm,"%lu%03ld",time, ms);
printf("Time : %s\n", tm);
}

void main() {
get_time_in_ms();
}

关于clock_gettime API 给出负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31911799/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com