#include <chrono> #include <ctime> #include <future> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <thread> #include <unistd.h> #include <uuid/uuid.h> 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::stringstream ss; 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()); ss << std::put_time(&tm_info, "%Y%m%d%H%M%S") << std::setw(3) << std::setfill('0') << std::to_string(mills.count() - seconds.count() * 1000) << std::setw(3) << std::setfill('0') << 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(); } char *uuid_value = (char *)malloc(40); char *get_uuid() { uuid_t new_uuid; uuid_generate(new_uuid); uuid_unparse(new_uuid, uuid_value); return uuid_value; } void fill_promise(std::promise<std::string> *promise_obj,const int&len) { std::stringstream ss; for(int i=0;i<len;i++) { ss<<i+1<<","<<get_uuid()<<std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(100)); } std::cout<<get_time_now()<<",in "<<__FUNCTION__<<std::endl; promise_obj->set_value(ss.str()); } void thread_promise_get(const int &len) { std::promise<std::string> promise_obj; std::thread t1(fill_promise,&promise_obj,std::cref(len)); std::cout<<promise_obj.get_future().get()<<std::endl; t1.join(); } int main(int args, char **argv) { thread_promise_get(atoi(argv[1])); }
Compile
g++ -g -std=c++2a -I. *.cpp -o h1 -luuid
标签:std,now,set,chrono,get,promise,time,include From: https://www.cnblogs.com/Fred1987/p/17284712.html