日历时间转换
cpp
#include <stdio.h>
#include <time.h>
int main()
{
time_t timep;
struct tm *localtmp;
struct tm *gmtmp;
timep = time(NULL);
gmtmp = gmtime(&timep);
printf("gmtmp :%s", asctime(gmtmp));
localtmp = localtime(&timep);
printf("localtmp :%s", asctime(localtmp));
printf("ctime :%s", ctime(&timep));
timep = mktime(gmtmp);
printf("gmtieme :%ld\n",timep);
timep = mktime(localtmp);
printf("localtmp :%ld\n",timep);
}

指定日期转换形式
cpp
#include <stdio.h>
#include <time.h>
int main ()
{
time_t rawtime;
struct tm *info;
char buffer[80];
time(&rawtime);
info = localtime(&rawtime);
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", info);
printf("本地时间 : |%s|\n", buffer);
info = gmtime(&rawtime);
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", info);
printf("UTC时间 : |%s|\n", buffer);
return (0);
}

获取时间
cpp
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
int main(void)
{
struct timeval tvStart, tvEnd;
struct timespec timeStart, timeEnd;
double fTimeInterval = 0.0;
int i = 0;
for (i = 0; i < 3; i++)
{
// --- Test gettimeofday ---
gettimeofday(&tvStart, NULL);
usleep(50000); // Delay for 50ms
gettimeofday(&tvEnd, NULL);
// Calculate elapsed time in milliseconds
fTimeInterval = (tvEnd.tv_sec - tvStart.tv_sec) * 1000.0 +
(tvEnd.tv_usec - tvStart.tv_usec) * 0.001;
printf("gettimeofday = %f ms\n", fTimeInterval);
// --- Test clock_gettime ---
clock_gettime(CLOCK_REALTIME, &timeStart);
usleep(50000); // Delay for 50ms
clock_gettime(CLOCK_REALTIME, &timeEnd);
// Calculate elapsed time in milliseconds
fTimeInterval = (timeEnd.tv_sec - timeStart.tv_sec) * 1000.0 +
(timeEnd.tv_nsec - timeStart.tv_nsec) * 0.000001;
printf("clock_gettime = %f ms\n", fTimeInterval);
}
return 0;
}