cpp get exact time and precision reach nanoseconds via std::chrono::high_resolution_clock

#include <chrono>
#include <ctime>
#include <iomapip>
#include  <iostream>
#include <sstream>


std::string get_time_now()
{
    std::chrono::time_point<std::chrono::high_resolution_clock> now = std::chrono::high_resolution_clock::now();
    time_t raw_time = std::chrono::high_resolution_clock::to_time_t(now);
    struct tm tm_info = *localtime(&raw_time);
    std::chrono::seconds seconds = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch());
    std::chrono::milliseconds mills = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
    std::chrono::microseconds micros = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch());
    std::chrono::nanoseconds nanos = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch());
    std::stringstream ss;
    ss << std::put_time(&tm_info, "%Y%m%d%H%M%S") << std::setfill('0') << std::setw(3) << std::to_string(mills.count() - seconds.count() * 1000)
       << std::setfill('0') << std::setw(3) << std::to_string(micros.count() - mills.count() * 1000) << std::setw(3) << std::setfill('0') << std::to_string(nanos.count() - micros.count() * 1000);
    return ss.str();
}

int main(int args,char **argv)
{
int len=atoi(argv[1]);
  for(int i=0;i<len;i++)
{
   std::cout<<i+1<<","<<get_time_now()<<std::endl;
}
}

cpp get exact time and precision reach nanoseconds via std::chrono::high_resolution_clock

 

原文链接: https://www.cnblogs.com/Fred1987/p/17279598.html

欢迎关注

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

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

    cpp get exact time and precision reach nanoseconds via std::chrono::high_resolution_clock

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

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

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

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

(0)
上一篇 2023年4月19日 上午9:07
下一篇 2023年4月19日 上午9:08

相关推荐