ctime、chrono以及所有和时间有关的内容

中文标准文档:日期和时间工具chrono

一、std::chrono

  1. duration_cast(这个主要实现的功能就是可以将单位进行转换,比如说我们获取到的系统时间可能是毫秒,但是我们要把他换算成秒怎么办,就用这个)。

  2. system_clock::now(这个函数的主要目的就是获取到当前系统时间,注意这个时间是当前时间与1970年1月1之间的差值,单位是time_point)

  3. time_since_porch (这个函数也是当前时间与1970年1月1日之间的差值,单位是duration)

  4. localtime(间隔)(这个函数可以将当前时间与1970年的差值,转换成包含今天年月日的结构体,不过注意,传进去的一定是秒)

  5. strftime函数(这个函数可以将结构体指针转换成包含时间格式的字符串数组)

  6. to_time_t(将timepoint时间转换成time_t)

尽量不要使用 count() 和 time_since_epoch(),因为这两个函数没有提供类型安全机制。

1.time_since_epoch():返回此time_pointclock的纪元间的时间量

2.count():返回此duration的计次数。

二、获取本地时间

1.C版本以及Windows API

#include <iostream>
#include <Windows.h>
#include <string>
#include <fstream>

int main()
{
    //system("time");  //将当前时间输出到控制台(黑框),并且可以输入时间修改系统时间

    //SYSTEMTIME SysTime;     //需要包含windows.h头文件
    //GetLocalTime(&SysTime); //得到本地时间,不再需要转换,就是当前时区的时间
    //SysTime.wYear;            //年份,类型为unsigned short
    //SysTime.wMonth;            //月份
    //SysTime.wDay;            //天
    //SysTime.wHour;            //小时
    //SysTime.wMinute;        //分钟
    //SysTime.wSecond;        //秒
    //SysTime.wMilliseconds;    //毫秒
    //SysTime.wDayOfWeek;        //一周的第几天(每周的星期一是第一天)

    //time_t timer;
    //time(&timer);
    //tm* tm1 = nullptr;
    ////tm = localtime(&timer); //报错:C4996会提示不安全
    //localtime_s(tm1,&timer);

    char szTimer[MAX_PATH];  //MAX_PATH需要包含windows.h
    tm tm2;
    time_t now;
    time(&now);  //获取系统日期和时间
    localtime_s(&tm2, &now);
    strftime(szTimer, _countof(szTimer), "%Y%m%d%H%M%S", &tm2);
    //strftime使用参考:http://www.cplusplus.com/reference/ctime/strftime/
    //localtime_r运行于linux下


    //SYSTEMTIME systime;
    //GetLocalTime(&systime);
    //auto year = systime.wYear;
    //char ct[MAX_PATH] = { 0 };
    //sprintf_s(ct, MAX_PATH, "%04d-%04d-%04d", systime.wYear, systime.wMonth, systime.wDay);
    //std::string str = ct;
    //std::string str2 = "Hello";
    //std::string str3 = str2 + str + std::string("HHHH");
    //SYSTEMTIME SysTime;  //需要包含windows.h头文件
    //GetLocalTime(&SysTime);
    //char ct[MAX_PATH];
    //sprintf_s(ct, MAX_PATH, "%04d%02d%02d%02d%02d%02d", SysTime.wYear, SysTime.wMonth, SysTime.wDay, SysTime.wHour, SysTime.wMinute, SysTime.wSecond);
    //std::ofstream outfile;
    //std::string path = "C:\\Users\\Yang\\Desktop\\dump";
    //path = path + ct + std::string(".txt");
    //outfile.open(path);

    return 0;
}

2. C++版本

#include <iostream>
#include <chrono>

// 获取系统当前时间
std::string getCurrentSystemTime()
{
    auto tt = std::chrono::system_clock::to_time_t
    (std::chrono::system_clock::now());
    struct tm* ptm = localtime(&tt);
    char date[60] = { 0 };
    sprintf(date, "%d-%02d-%02d-%02d.%02d.%02d",
        (int)ptm->tm_year + 1900, (int)ptm->tm_mon + 1, (int)ptm->tm_mday,
        (int)ptm->tm_hour, (int)ptm->tm_min, (int)ptm->tm_sec);
    return std::string(date);
}

三、获取代码执行所用时间

1.方式一:

clock() :返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,不是秒也不是毫秒

CLOCKS_PER_SEC : 表示一秒钟会有多少个时钟计时单元,vs中有如下定义:

// The number of clock ticks per second
#define CLOCKS_PER_SEC  ((clock_t)1000)

使用示例

#include <iostream>
//#include <ctime> //iostream包含ctime

int main()
{
    clock_t start, end;
    start = clock();
    for (int i = 0; i < 10000; i++)
    {
        std::cout << i;
    }
    end = clock();
    std::cout << "\nTime:" << static_cast<long>(end - start) << '\n';
    return 0;
}

2.方式二:

C++标准库提供了三个用来计时的函数

  • steady_clock 是单调的时钟,相当于教练手中的秒表;只会增长,适合用于记录程序耗时;

  • system_clock 是系统的时钟;因为系统的时钟可以修改;甚至可以网络对时; 所以用系统时间计算时间差可能不准。

  • high_resolution_clock 是当前系统能够提供的最高精度的时钟;它也是不可以修改的。相当于 steady_clock 的高精度版本。

//时长,时间类型转换
#include <iostream>
#include <chrono>

int main()
{
    const auto before = std::chrono::system_clock::now();

    for (int i = 0; i < 10000; i++)
    {
        std::cout << i;
    }

    //std::chrono::duration_cast<std::chrono::milliseconds>(time)用于将time转换为毫秒
    const auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - before);
    std::cout << "\nIt took: " << duration.count() / 1000.0 << "s" << std::endl;  //花费多少秒
    return 0;
}

四、线程等待时间

    using namespace std::chrono_literals;
    std::this_thread::sleep_for(5s);   //5s
    std::this_thread::sleep_for(100ms);//100ms
    std::this_thread::sleep_for(std::chrono::seconds(3));  //3s
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));  //1000ms = 1s

原文链接: https://www.cnblogs.com/mmmmmmmmm/p/14157184.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    ctime、chrono以及所有和时间有关的内容

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/404217

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月24日 下午6:45
下一篇 2023年4月24日 下午6:45

相关推荐