如何使用 time.h 获取 UTCTime 中秒的小数部分
我想获取系统时间,包括秒的小数部分。标准c(ANSI C)可以吗? 如果没有,请告诉我一些 Windows 操作系统的库,以便我使其成为可能。在 Linux 中,我有以下代码,可以正常工作。
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char buffer[30];
struct timeval tv;
time_t curtime;
gettimeofday(&tv, NULL);
curtime=tv.tv_sec;
strftime(buffer,30,"%m-%d-%Y %T.",localtime(&curtime));
printf("%s%ld\n",buffer,tv.tv_usec);
return 0;
}
输出是
12-25-2009 11:09:18.35443541
请帮助我,window 操作系统怎么可能。如果 ANSI C 不允许我。
I want to get the system time including fractional part of the seconds. Is it possible in standard c (ANSI C)?
If not then tell me some libraries for window OS so that I make it possible. In Linux I have the following code with work fine for me.
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char buffer[30];
struct timeval tv;
time_t curtime;
gettimeofday(&tv, NULL);
curtime=tv.tv_sec;
strftime(buffer,30,"%m-%d-%Y %T.",localtime(&curtime));
printf("%s%ld\n",buffer,tv.tv_usec);
return 0;
}
Output is
12-25-2009 11:09:18.35443541
Kindly help me, how is it possible for window OS. IF ANSI C doesn't allow me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
标准 C 不提供亚秒级分辨率计时。
POSIX 确实提供了亚秒级分辨率计时 - 事实上,有许多不同的方法来实现它,包括您展示的 gettimeofday() 。
Standard C does not provide sub-second resolution timing.
POSIX does provide sub-second resolution timing - in fact, a number of different ways of doing it, including
gettimeofday()
which you show.像这样:
如果性能对您很重要,那么有几点:
1)
gettimeofday()
相当快,如果在几个线程中使用,它不会导致性能恶化2)内部< code>localtime() 有一个对
pthread_mutex_lock()
的调用(可能是因为它需要一些系统设置,例如白天)。因此,当您在多线程应用程序中广泛使用它时,可能会出现性能问题Like this:
Couple of points about performance if it is important to you:
1)
gettimeofday()
is quite fast and if is used in a few threads it doesn't cause worsenig of performance2) Inside
localtime()
there is a call topthread_mutex_lock()
(probably because it needs some system settings like daytime). So when you use it extensively in a multithreaded application there might performance problems上面的代码在
大多数情况下都可以工作,但对于较小的 tv.tv_usec 值来说是不正确的。
如果 tv.tv_usec 是 123,它会在应该打印
HH:MM:SS.000123
时打印HH:MM:SS.123
试试这个:
In the above code
will work most of the time but it is not correct for small tv.tv_usec values.
If tv.tv_usec is 123, it will print
HH:MM:SS.123
when it should printHH:MM:SS.000123
Try this: