C 获取本地时间(毫秒)
我需要最快的方法来获取本地时间(因此考虑到当前时区),至少以毫秒为单位,如果可以以十分之一毫秒为单位,则会更好 我希望避免使用C 获取本地时间(毫秒),c,datetime,time,C,Datetime,Time,我需要最快的方法来获取本地时间(因此考虑到当前时区),至少以毫秒为单位,如果可以以十分之一毫秒为单位,则会更好 我希望避免使用gettimeofday(),因为它现在是一个过时的函数 因此,似乎我需要使用时钟\u gettime(clock\u REALTIME,…)并将小时调整到当前时区,但如何调整?那么这样做的最佳点在哪里呢?在存储clock_gettime获得的时间戳之前,还是在将其转换为当前时区的公历之前 编辑:我的原始示例加入了获取时钟和本地时间的功能-有更好的方法实现这一功能吗 #i
gettimeofday()
,因为它现在是一个过时的函数
因此,似乎我需要使用时钟\u gettime(clock\u REALTIME,…)
并将小时调整到当前时区,但如何调整?那么这样做的最佳点在哪里呢?在存储clock_gettime获得的时间戳之前,还是在将其转换为当前时区的公历之前
编辑:我的原始示例加入了获取时钟和本地时间的功能-有更好的方法实现这一功能吗
#include <time.h>
#include <stdio.h>
int main() {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
struct tm* ptm;
ptm = localtime(&(ts.tv_sec));
// Tenths of milliseconds (4 decimal digits)
int tenths_ms = ts.tv_nsec / (100000L);
printf("%04d-%02d-%02d %02d:%02d:%02d.%04d\n",
1900 + ptm->tm_year, ptm->tm_mon + 1, ptm->tm_mday,
ptm->tm_hour, ptm->tm_min, ptm->tm_sec, tenths_ms);
}
#包括
#包括
int main(){
结构timespects;
时钟获取时间(时钟实时,&ts);
struct tm*ptm;
ptm=本地时间(&(ts.tv_秒));
//十分之一毫秒(4位十进制数字)
十分之一毫秒=ts.tv/(100000升);
printf(“%04d-%02d-%02d%02d:%02d:%02d.%04d\n”,
1900+ptm->tm年,ptm->tm月+1,ptm->tm日,
ptm->tm_小时,ptm->tm_分钟,ptm->tm_秒,十分之一毫秒);
}
是的,这可以通过使用clock\u gettime()
函数来实现。在当前版本的POSIX中,gettimeofday()
被标记为过时。这意味着它可能会从规范的未来版本中删除。建议应用程序编写者使用clock\u gettime()
函数,而不是gettimeofday()
长话短说,下面是一个如何使用clock\u gettime()
的示例:
注意:时间()返回的自历元以来的秒数(以格林威治标准时间(GMT)为单位进行测量。我认为没有比使用
clock\u gettime()
和localtime()更好的方法了。然而,你需要正确地返回返回的纳秒,并考虑当时间被围拢到下一秒时的情况。要格式化时间,可以使用strftime()
而不是手动格式化tm
结构:
#包括
#包括
内部主(空){
结构timespects;
长毫秒;
int err=clock\u gettime(clock\u REALTIME,&ts);
如果(错误){
佩罗尔(“时钟时间”);
返回1;
}
//舍入纳秒到毫秒
如果(ts.tv\U nsec>=999500000){
ts.tv_sec++;
msec=0;
}否则{
msec=(ts.tv_nsec+500000)/1000000;
}
struct tm*ptm=localtime(&ts.tv_秒);
如果(ptm==NULL){
perror(“本地时间”);
返回1;
}
char time_str[sizeof(“1900-01-01 23:59:59”);
time_str[strftime(time_str),sizeof(time_str),
%Y-%m-%d%H:%m:%S,ptm)]='\0';
printf(“%s.%03li\n”,时间长度,毫秒);
}
但是,当前的时区调整怎么办?我已经编辑了我对您有关时区查询的回答。它给你一个获取时区的代码。现在,如何根据您的要求进行调整,留给您作为练习。谢谢。我已经编辑了这个问题,以显示我的原始测试,这促使我提出这个问题,我真的需要知道如何更推荐(快速)的方式达到这一点。
#define _POSIX_C_SOURCE 200809L
#include <inttypes.h>
#include <math.h>
#include <stdio.h>
#include <time.h>
void print_current_time_in_ms (void)
{
long ms; // Milliseconds
time_t s; // Seconds
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
s = spec.tv_sec;
ms = round(spec.tv_nsec / 1.0e6); // Convert nanoseconds to milliseconds
printf("Current time: %"PRIdMAX".%03ld seconds since the Epoch\n",
(intmax_t)s, ms);
}
#define _GNU_SOURCE /* for tm_gmtoff and tm_zone */
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t t = time(NULL);
struct tm lt = {0};
localtime_r(&t, <);
printf("Offset to GMT is %lds.\n", lt.tm_gmtoff);
printf("The time zone is '%s'.\n", lt.tm_zone);
return 0;
}