1)求 时间差(精确到微秒) int gettimeofday (struct timeval *__restrict __tv,__timezone_ptr_t __tz);
#include <stdio.h>
#include <sys/time.h>
int
main(void)
{
int i=0;
struct timeval tv,tv2;
gettimeofday(&tv, NULL);
for (i = 0; i < 100000; i++)
{
printf("%d\t",i+1);
if((i+1)%20 == 0) puts("\n");
}
gettimeofday(&tv2, NULL);
printf("\nsecond : %f", (tv2.tv_usec - tv.tv_usec)/1000000.0 + (tv2.tv_sec-tv.tv_sec) );
return 0;
}
2)求当前时间(精确到秒) time(0) 及时间的转换。
#include <time.h>
#include <stdio.h>
#include <string.h>
int
main()
{
time_t now = time(0);
const char * cnow = ctime(&now);
struct tm *ptmNow = localtime(&now);
char ctmnow[128] = { 0 };
printf("秒数:%d\n",now);
printf("原始时间:%s",cnow);
sprintf(ctmnow, "%4d-%02d-%02d %02d:%02d:%02d", 1900 + ptmNow->tm_year,
1+ptmNow->tm_mon,ptmNow->tm_mday,ptmNow->tm_hour,ptmNow->tm_min,ptmNow->tm_sec);
printf("手动转换为日期: %s\n",ctmnow);
strftime(ctmnow,sizeof(ctmnow),"自动转换的日期: %Y-%m-%d %H:%M:%S",ptmNow); //格式化时间
//strftime(ctmnow,sizeof(ctmnow),"自动转换的日期: %F %T",ptmNow); //或格式化时间
printf("%s\n",ctmnow);
return 0;
}
3)时间函数相互关系