#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/timeb.h>
#include <Windows.h>
struct timeb timenow;
int main() {
ftime(&timenow);
printf("%ds %dms\n", timenow.time, timenow.millitm);
Sleep(1503);
ftime(&timenow);
printf("%ds %dms\n", timenow.time, timenow.millitm);
return 0;
}
Why the program always print 0 ms ? The time is OK but the millitm is always 0.
According to ftime(3) - Linux manual page , the time
member of struct timeb
has the type time_t
.
This type may be 64-bit long to support date beyond the year 2038.
On the other hand, typical int
is 32-bit long.
The %d
format specifier is for printing int
, and passing time_t
to that will invoke undefined behavior by passind data having wrong type.
Unfortunately printf
doesn't seem to have proper format specifier to print time_t
, so you should cast that to some type that can be safely printed via printf
.
On the other hand, the millitm
member is unsigned short
and it will be promoted to int
, so using %d
fot that is fine.
Try this:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/timeb.h>
#include <Windows.h>
#include <inttypes.h>
struct timeb timenow;
int main() {
ftime(&timenow);
printf("%" PRId64 "s %dms\n", (int64_t)timenow.time, timenow.millitm);
Sleep(1503);
ftime(&timenow);
printf("%" PRId64 "s %dms\n", (int64_t)timenow.time, timenow.millitm);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.