cpp get current time and its precision reach milliseconds even micros

#include <chrono>
#include <functional>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <thread>
#include <unistd.h>


std::string get_time_now() { 
    std::chrono::high_resolution_clock::time_point  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::milliseconds mills=std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
    std::chrono::seconds seconds =std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch());
    std::chrono::microseconds micros=std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch());
    std::uint64_t mills_count=mills.count()-seconds.count()*1000;
    std::uint64_t micros_count=micros.count()-mills.count()*1000;
    // std::cout<<"mills = "<<mills_count<<std::endl;
    std::cout<<"nMills="<<mills_count<<",Micros="<<micros_count<<std::endl;
    std::stringstream ss;
    ss<<std::put_time(&tm_info,"%Y%m%d%H%M%S")<<std::setfill('0')<<std::setw(3)<<mills_count<<std::setfill('0')
    <<std::setw(3)<<micros_count;
    return ss.str();
}

int main(int args, char **argv) {
    int x=atoi(argv[1]);
    int y=atoi(argv[2]);
     std::thread t1([](int xx,int yy) {
        for(int i=0;i<xx;i++) {
            std::cout<<"I="<<i<<",now is "<<get_time_now()<<std::endl;
            usleep(100);
        }
        for(int i=0;i<yy;i++) {
            std::cout<<"Now is "<<get_time_now()<<","<<i<<std::endl;
            usleep(100);
        }
     },x,y);
     t1.join();
     std::cout<<get_time_now()<<",finished in "<<__FUNCTION__<<std::endl;
}

 

Compile

g++ -g -std=c++2a -I. *.cpp -o h1 -luuid -lpthread

 

Run

./h1 100 100

cpp get current time and its precision reach milliseconds even micros

 

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

欢迎关注

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

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

    cpp get current time and its precision reach milliseconds even micros

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

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

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

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

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

相关推荐