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;
}