Linux 编程——获取时间戳,精确到毫秒,sleep

Linux 编程——获取时间戳,精确到毫秒_gettimeofday(&time_, null); 时间戳-CSDN博客

几种获取系统时间戳方式的对比 - 简书

c++实现获取当前时间(精确至秒,毫秒和微妙)_C 语言_脚本之家

// 获取当前时间的时间戳

#include <iostream>
#include <chrono>
#include <thread>

int main()
{
    auto currentTime = std::chrono::system_clock::now();
    auto currentTime_s = std::chrono::time_point_cast<std::chrono::seconds>(currentTime);
    auto currentTime_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(currentTime);
    auto currentTime_micro = std::chrono::time_point_cast<std::chrono::microseconds>(currentTime);
    auto currentTime_ns = std::chrono::time_point_cast<std::chrono::nanoseconds>(currentTime);
    auto valueS = currentTime_s.time_since_epoch().count();
    auto valueMS = currentTime_ms.time_since_epoch().count();
    auto valueMicroS = currentTime_micro.time_since_epoch().count();
    auto valueNS = currentTime_ns.time_since_epoch().count();

    std::cout << "Seconds: " << valueS << std::endl;
    std::cout << "Milliseconds: " << valueMS << std::endl;
    std::cout << "Microseconds: " << valueMicroS << std::endl;
    std::cout << "Nanoseconds: " << valueNS << std::endl;
 

std::this_thread::sleep_for(std::chrono::milliseconds(10));

    return 0;
}

/* 日志时间戳,精确到毫秒 */
char* get_stime(void)
{ 
    static char timestr[200] ={0};
    struct tm * pTempTm;
    struct timeval time;
        
    gettimeofday(&time,NULL);
    pTempTm = localtime(&time.tv_sec);
    if( NULL != pTempTm )
    {
        snprintf(timestr,199,"%04d-%02d-%02d %02d:%02d:%02d.%03ld",
            pTempTm->tm_year+1900,
            pTempTm->tm_mon+1, 
            pTempTm->tm_mday,
            pTempTm->tm_hour, 
            pTempTm->tm_min, 
            pTempTm->tm_sec,
            time.tv_usec/1000);
    }
    return timestr;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值