2014-11-16 11:29:15|?次阅读|上传:wustguangh【已有?条评论】发表评论
C/C++语言提供了用字符串格式表示时间的函数。
char * asctime(const struct tm *) char * ctime(const time_t *)
这两个函数返回值都是一个表示时间的字符串,区别在于传入的参数不同。
#include <iostream>
#include <time.h>
using namespace std;
int main(void)
{
time_t nowtime;
nowtime = time(NULL); //获取日历时间
cout << nowtime << endl; //输出nowtime
struct tm *local;
local=localtime(&nowtime); //获取当前系统时间
cout << asctime(local) ;
cout << ctime(&nowtime) ;
return 0;
}
输出结果:
1268575163
Sun Mar 14 13:59:23 2010
Sun Mar 14 21:59:23 2010
可以通过difftime来计算两个时间的间隔,可以精确到秒,函数原型:
double difftime(time_t, time_t)
要想精确到毫秒,就要使用clock函数了,函数原型:
clock_t clock(void)
从定义可以看出clock返回一个clock_t类型,这个类型也定义在time.h中,原型是:
typedef long clock_t
clock_t也是一个长整型,表示的是从程序开始运行到执行clock函数时所经过的cpu时钟计时单元数。
#include <iostream>
#include <time.h>
using namespace std;
int main(void)
{
time_t start, ends;
clock_t cstart,cends;
start=time(NULL);
cstart=clock();
system("pause");
ends=time(NULL);
cends=clock();
cout << "时间差:" << difftime(ends,start) << endl;
cout << "Clock时间差:" << cends-cstart << endl;
return 0;
}
输出结果:
请按任意键继续. . .
时间差:3
Clock时间差:3094
在time.h中定义了一个CLOCKS_PER_SEC
/* Clock ticks macro - ANSI version */
#define CLOCKS_PER_SEC 1000
表示1秒钟内有多少个时钟计时单元,在标准C/C++中,最小的计时单位是1毫秒。