#include <assert.h> #include <atomic> #include <chrono> #include <fstream> #include <iomanip> #include <iostream> #include <mutex> #include <numeric> #include <thread> #include <unistd.h> #include <uuid/uuid.h> #include <vector> char *uuid_value = (char *)malloc(40); char *get_uuid_value() { uuid_t new_uuid; uuid_generate(new_uuid); uuid_unparse(new_uuid, uuid_value); return uuid_value; } std::string get_time_now(bool is_exact = false) { 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; ss << std::put_time(&tm_info, "%Y%m%d%H%M%S"); if (is_exact) { auto seconds = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()); auto mills = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()); auto micros = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()); auto nanos = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()); ss << std::setw(3) << std::setfill('0') << (mills.count() - seconds.count() * 1000) << std::setw(3) << std::setfill('0') << (micros.count() - mills.count() * 1000) << std::setw(3) << std::setfill('0') << (nanos.count() - micros.count() * 1000); } return ss.str(); } void write_file(const std::string &file_name, const int &loops) { std::fstream w_file(file_name, std::ios::app); if (!w_file.is_open()) { std::cout << "Create or open " << file_name << " failed!" << std::endl; return; } static std::uint64_t num = 0; std::stringstream ss; for (int i = 0; i < loops; i++) { for (int j = 0; j < 1000000; j++) { ss << ++num << "," << get_uuid_value() << std::endl; } w_file << ss.str(); ss = std::stringstream(); std::cout << get_time_now(true) << ",num:" << num << ",loop:" << i + 1 << std::endl; if (!w_file.good()) { std::cout << get_time_now(true) << ",num:" << num << ",loop:" << i + 1 << ",write failed!" << std::endl; break; } } w_file.close(); std::cout << get_time_now(true) << ",num:" << num << ",finish in " << __FUNCTION__ << std::endl; } int main(int args, char **argv) { try { write_file(argv[1], atoi(argv[2])); } catch (const std::exception &e) { std::cerr << e.what() << '\n'; } }
Compile
g++ -std=c++2a -I. *.cpp -o h1 -luuid
Run
./h1 log.txt 100000
标签:files,std,now,via,filstream,uuid,chrono,time,include From: https://www.cnblogs.com/Fred1987/p/17433133.html