函数库 time.h,sys/time.h 关于时间的用法

5 篇文章 0 订阅

time.h

一. struct tm*

使用时间最重要的结构体就是掌握struct tm*的用法
在这个结构体中有年月日时分秒,掌握了这个结构体之后我们就可以输出时间。
1.首先 time_t rawtime 创建一个未经处理的时间
2.这个rawtime还没有与本地时间同步,所以需要 time(&rawtime) ,此时rawtime已经与本地时间同步了,但是此时的rawtime仍为一串数字,还要再经历转换。
3.此时创建结构体 struct tm* timeinfo , 并将 rawtime转换成当地时间的书写形式, localtime(&rawtime) , 此时我们便得到了时间的结构体信息,就可以对它为所欲为了。

void test0()
{
    time_t rawtime;
    time(&rawtime);
    struct tm *timeinfo = localtime(&rawtime);
    cout << timeinfo->tm_year + 1900 << "年" << endl;
    cout << timeinfo->tm_mon + 1 << "月" << endl;
    cout << timeinfo->tm_mday << "日" << endl;
    cout << timeinfo->tm_hour << "时" << endl;
    cout << timeinfo->tm_min << "分" << endl;
    cout << timeinfo->tm_sec << "秒" << endl;
    cout << "星期" << timeinfo->tm_wday << endl;
}

二. char* asctime(const struct tm* timeinfo)

利用函数库中的输出时间,也就是 asctime 函数, 可以直接输出格式化好的时间。
输出格式如下:
Thu May 14 15:18:00 2020

void test1()
{
    time_t rawtime;
    time(&rawtime);

    struct tm *timeinfo;
    timeinfo = localtime(&rawtime);
    cout << asctime(timeinfo) << endl;
}

输出:

wwx@VM-0-7-ubuntu:~/Linux/Day04/ctime$ cd "/home/wwx/Linux/Day04/ctime/" && g++ main.cpp -o main && "/home/wwx/Linux/Day04/ctime/"main
Mon May 18 13:20:35 2020


sys/time.h

此头文件只能在linux环境下使用,主要用于计算程序的时间差。

  • 结构体timeval

         struct timeval {
             time_t      tv_sec;     /* seconds */
             suseconds_t tv_usec;    /* microseconds */
         };
    

tv_sec 代表从1970年1月1日起经过的秒数,tv_usec则标识微秒,另外
一秒 == 1000000微秒。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <string.h>
#include <iostream>
#include <sys/time.h>
using namespace std;

int main()
{
    struct timeval beg, end;
    gettimeofday(&beg, NULL);
    sleep(1);
    gettimeofday(&end, NULL);
    cout << "针对秒级别:" << endl;
    cout << beg.tv_sec << endl;
    cout << end.tv_sec << endl;
    cout << end.tv_sec - beg.tv_sec << endl;

    cout << "针对微秒级别:" << endl;
    cout << beg.tv_usec << endl;
    cout << end.tv_usec << endl;
    cout << end.tv_usec - beg.tv_usec << endl;

    return 0;
}
  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值