hulubrother

c++ 的时间函数定义在 <ctime>(time.h) 文件中

 

文件中常量:

  CLOCKS_PER_SEC: 官方描述: Clock ticks per second (macro ) 

     正是因为这个每秒滴答数的定义不同,在Linux 和windows 平台下会产生不同的时间表述方法,所以不建议使用这个类的函数来计算时间差,而是希望采用 chrono 库来计算

  NULL:

cout << "ctime / time.h 类测试 函数" << std::endl;
    cout << "常量:" << std::endl;
    cout << CLOCKS_PER_SEC << endl;
    time_t current_time = time(0);            // 表示自UTC(1970年1月1日)00:00小时起经过的秒数 time() 函数产生
    clock_t begin = clock();            // 获取计算机的嘀嗒数
    struct tm *current_utf_time = gmtime(&current_time);
    struct tm *current_local_time = localtime(&current_time);

    cout << "time_t is : " << current_time << endl;
    cout << "clock is : " << begin << endl;
    cout << "time_t 转成字符串 : " << ctime(&current_time) << endl;
    cout << "struct UTC tm 转成字符串 : " << asctime(current_utf_time) << endl;
    cout << "struct local tm 转成字符串 : " << asctime(current_local_time) << endl;

    struct tm y2k = { 0 };
    y2k.tm_sec = 0;
    y2k.tm_min = 0;
    y2k.tm_hour = 0;
    y2k.tm_mday = 1;
    y2k.tm_mon = 0; 
    y2k.tm_year = 100; 

    
    double seconds = difftime(current_time, mktime(&y2k));
    cout << "距离 2000 01/01 00:00:00 时间秒数为:" << seconds << endl;

    time_t end_time = time(0);
    clock_t end = clock();

    cout << "time_t 时间差 :" << (end_time - current_time) << "s" << endl;
    cout << "clock 时间差为 : " << (end - begin) / CLOCKS_PER_SEC << "s" << endl;


    char buffer[80];
    strftime(buffer, 80, "Now it\'s %I:%M%p.", current_utf_time);
    cout << buffer << endl;

运行完上面的标准库后,你会惊喜的发现,编译中有一些安全警告,建议你在更换这些方法

分类:

技术点:

相关文章: