您的位置:首页 > 编程语言 > C语言/C++

C/C++时间函数总结

2017-03-27 15:14 387 查看
C语言的时间函数

-------- 头文件
time.h
-------- 相关函数和接口
asctime() 将时间日期以字符串格式表示
ctime() 将时间日期以字符串格式表示
gettimeofday() 获取当前时间
gmtime() 获取当前时间和日期
localtime() 获取当前时间和日期并转换为本地时间
mktime() 将时间转换成经过的秒数
settimeofday() 设置当前时间戳
time() 获取当前时间(以秒数表示)

struct tm*gmtime(const time_t*timep);
int gettimeofday ( struct timeval * tv , struct timezone * tz )
char *ctime(const time_t *timep);
struct tm *localtime(const time_t * timep);
time_t mktime(strcut tm * timeptr);
int settimeofday ( const struct timeval *tv,const struct timezone *tz);

time_t 是一个长整型数
tm 结构体类型
timeval 包含秒和微秒的结构体

-------- 例子

#include <time.h>
main() {
time_t timep;
time (&timep);
printf("%s",asctime(gmtime(&timep)));
}


C++ 语言的时间函数

标准库没有提供所谓的日期类型。C++ 继承了 C 语言用于日期和时间操作的结构和函数。

Windows 平台的时间函数

-------- 头文件
<windows.h>
-------- 相关函数和接口
GetSystemTime 获得UTC(等于GMT)时间

GetLocalTime 获得系统本地时间

-------- 例子

#include <windows.h>
#include <stdio.h>

void main()
{
SYSTEMTIME st, lt;

GetSystemTime(&st);
GetLocalTime(<);

printf("The system time is: %02d:%02d\n", st.wHour, st.wMinute);
printf("The local time is: %02d:%02d\n", lt.wHour, lt.wMinute);
}


Linux 平台的时间函数

-------- 头文件
<sys/time.h>

-------- 相关函数和接口
int gettimeofday(struct timeval *restrict tp, void *restrict tzp);

-------- 例子

#include <stdio.h>
#include <sys/time.h>

int main() {
struct timeval start, end;

gettimeofday( &start, NULL );
sleep(3);
gettimeofday( &end, NULL );

//求出两次时间的差值,单位为us
int timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec;
printf("time: %d us\n", timeuse);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: