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

 

posted @ 2023-02-02 17:54  FredGrit  阅读(11)  评论(0编辑  收藏  举报