Linux c和cpp如何获取真实时间和绝对时间

使用这些函数的组装可以用来记录程序执行时间,和执行时长

#include 
#include 
#include 
#include 
#include 

// 真实世界的挂钟时间
void get_real_time()
{
    //  time ------>sec
    time_t second1;
    time(&second1);
    time_t second2 = time(NULL);
    printf("sec1=%ld    sec2 = %ld\n", second1, second2);
    struct tm *p = gmtime(&second1); // 格林尼治时间
    printf("%d-%d-%d  %d:%d:%d\n", p->tm_year + 1900, p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec);
    struct tm *p2 = localtime(&second1); // 本地时间
    printf("%d-%d-%d  %d:%d:%d\n", p2->tm_year + 1900, p2->tm_mon + 1, p2->tm_mday, p2->tm_hour, p2->tm_min, p2->tm_sec);
    struct tm Stime;
    localtime_r(&second1, &Stime); // 线程安全 格林尼治时间同理
    printf("%d-%d-%d  %d:%d:%d\n", Stime.tm_year + 1900, Stime.tm_mon + 1, Stime.tm_mday, Stime.tm_hour, Stime.tm_min, Stime.tm_sec);
    printf("%s\n", asctime(p2)); // 倒序打印时间

    // gettimeofday ------->ms
    struct timeval microsecond;
    gettimeofday(µsecond, NULL);
    printf("gettimeofday sec = %ld,microsecond = %ld\n", microsecond.tv_sec, microsecond.tv_usec);
    struct tm *p3 = localtime(µsecond.tv_sec); // 本地时间
    printf("%d-%d-%d  %d:%d:%d\n\n", p3->tm_year + 1900, p3->tm_mon + 1, p3->tm_mday, p3->tm_hour, p3->tm_min, p3->tm_sec);

    // clock_gettime------->ns
    struct timespec tv;
    clock_gettime(CLOCK_REALTIME, &tv);
    printf("clock_gettime sec = %ld,microsecond = %ld\n\n", tv.tv_sec, tv.tv_nsec);

    // cpp chroro 获取任意时间 时间段duration 时间点time_point
    // time_point 同类型相减等到duration time_point和 duration相加减等到 time_point
    std::chrono::system_clock::time_point today = std::chrono::system_clock::now();
    std::cout << std::chrono::duration_cast(today.time_since_epoch()).count() << std::endl;
    std::cout << std::chrono::duration_cast(today.time_since_epoch()).count() << std::endl;
    std::cout << std::chrono::duration_cast(today.time_since_epoch()).count() << std::endl;
    std::cout << std::chrono::duration_cast(today.time_since_epoch()).count() << std::endl;
    auto todaycont = std::chrono::duration_cast(today.time_since_epoch()).count();
    std::cout << typeid(todaycont).name() << "   " << todaycont << std::endl;
    // 和time_t 进行转换
    std::time_t second3 = std::chrono::system_clock::to_time_t(today);
    std::cout << "time_t = " << second3 << std::endl;
}
// 系统启动时间
void get_system_start_time()
{
    // linux
    struct timespec tv;
    clock_gettime(CLOCK_MONOTONIC, &tv);
    printf("clock_gettime sec = %ld,microsecond = %ld\n\n", tv.tv_sec, tv.tv_nsec);
    // cpp
    auto now = std::chrono::steady_clock::now();
    std::cout << std::chrono::duration_cast(now.time_since_epoch()).count() << std::endl;
    std::cout << std::chrono::duration_cast(now.time_since_epoch()).count() << std::endl;
}
int main()
{
    get_real_time();
    get_system_start_time();
    return 0;
}

你可能感兴趣的:(c语言编程,c++,数据库,c语言,后端,音视频)