时间相关 time() ctime time_t localtime() gettimeofday

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)时间函数相互关系


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值