因为看程序看到了系统时间获取这块,所以在网上查了些资料并且自己实现了一遍,为了防止自己忘记,记录下来,以便于日后查询
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <unistd.h>
using namespace std;
void Delay(int time);
int main()
{
time_t now_time; //time_t是一个长整型变量(long),能够表示的时间是有限的
//time()函数的入口函数是一个time_t类型的指针
now_time = time(NULL);//获取系统时间,time()函数返回的是一个time_t类型的变量,表示的是从1970年1月
//1日0时0分0秒到此时的秒数
cout << "time: " << now_time << endl;
//tm是一个结构体,这个机构定义了年、月、日、时、分、秒、星期、当年中的某一天、夏令时。
struct tm* local_time;
//localtime()函数的入口函数为time_t类型的指针,返回变量类型为struct tm*
local_time = localtime(&now_time);
//tm结构体中表示的年份代表的是从1900年开始算经过了多少年,所以在实际输出时需要加上1900
cout << "localtime: " << (local_time->tm_year)+1900 << endl;
//用字符串格式表示时间
//char* asctime(const struct tm*)
cout << asctime(local_time) << endl;
cout << "**************" << endl;
//char* ctime(const time_t*)
cout << ctime(&now_time) << endl;
cout << "calcute time below: " << endl;
time_t start_t,end_t;
clock_t start_c,end_c;
start_t = time(NULL);
//clock()返回的是cpu时钟个数,并不是实际的时间
start_c = clock();
cout << "start_c: " << start_c << endl;
int i = 0;
//while(++i < 10)
//{
//system("pause");
//}
//Delay(5);
sleep(3);
end_t = time(NULL);
end_c = clock();
cout << "end_c: " << end_c << endl;
//double difftime(time_t,time_t)
cout << "time calculated by difftime function: " << difftime(end_t,start_t) << endl;
cout << "time calculated by clock minus: " << end_c - start_c << endl;
return 0;
}
void Delay(int time)
{
int count;
count = clock();
while(clock() - count < time*1000);
}
最后记录一下:
linux不能使用windows下的system(“pause”)函数,如果想实现延时效果,可以加入头文件 #include