c++中获取系统时间的方法

因为看程序看到了系统时间获取这块,所以在网上查了些资料并且自己实现了一遍,为了防止自己忘记,记录下来,以便于日后查询

#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值