首页 > 其他分享 >cpp generate uuid by random

cpp generate uuid by random

时间:2023-07-19 11:55:58浏览次数:42  
标签:std now end random start time cpp include generate

#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cstdint>

uint32_t rand32()
{
    return ((rand() & 0x3) << 30) | ((rand() & 0x7fff) << 15) | (rand() & 0x7fff);
}

bool gen_uuid4(char dst[37], size_t len)
{
    int n = snprintf(dst, len, "%08x-%04x-%04x-%04x-%04x%08x", 
        rand32(),                         // Generates a 32-bit Hex number
        rand32() & 0xffff,                // Generates a 16-bit Hex number
        ((rand32() & 0x0fff) | 0x4000),   // Generates a 16-bit Hex number of the form 4xxx (4 indicates the UUID version)
        (rand32() & 0x3fff) + 0x8000,     // Generates a 16-bit Hex number in the range [0x8000, 0xbfff]
        rand32() & 0xffff, rand32());     // Generates a 48-bit Hex number
        
    return n >= 0 && n < len;             // Success only when snprintf result is a positive number and the provided buffer was large enough.
}

int main()
{
    char strUuid[37];
    srand(time(NULL));
    
    bool success = gen_uuid4(strUuid, sizeof(strUuid));
    
    printf("%s\n", success ? strUuid : "UUID generation failed!");
    
    return 0;
}

 

 

#include <algorithm>
#include <chrono>
#include <ctime>  
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <thread>
#include <typeinfo> 
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cstdint>
 
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;
    ss << std::put_time(&tm_info, "%Y%m%d%H%M%S");
    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();
}

uint32_t rand32()
{
    return ((rand() & 0x3) << 30) | ((rand() & 0x7fff) << 15) | (rand() & 0x7fff);
}

void gen_uuid4(char dst[37], size_t len)
{
    snprintf(dst, len, "%08x-%04x-%04x-%04x-%04x%08x",
             rand32(),                       // Generates a 32-bit Hex number
             rand32() & 0xffff,              // Generates a 16-bit Hex number
             ((rand32() & 0x0fff) | 0x4000), // Generates a 16-bit Hex number of the form 4xxx (4 indicates the UUID version)
             (rand32() & 0x3fff) + 0x8000,   // Generates a 16-bit Hex number in the range [0x8000, 0xbfff]
             rand32() & 0xffff, rand32());   // Generates a 48-bit Hex number
}

void test_time_cost(const int &loops)
{
    char strUuid[37];
    std::chrono::time_point<std::chrono::high_resolution_clock> _start_time, _end_time;
    for (int i = 0; i < loops; i++)
    {
        _start_time = std::chrono::high_resolution_clock::now();

        for (int j = 0; j < 1000000; j++)
        {
            srand(time(NULL));
            gen_uuid4(strUuid, sizeof(strUuid));
        }
        _end_time = std::chrono::high_resolution_clock::now();
        std::cout << "Loops:" << i + 1 << ", time cost:"
                  << std::chrono::duration_cast<std::chrono::seconds>(_end_time - _start_time).count() << " seconds,"
                  << std::chrono::duration_cast<std::chrono::milliseconds>(_end_time - _start_time).count() << " mills,"
                  << std::chrono::duration_cast<std::chrono::microseconds>(_end_time - _start_time).count() << " micros,"
                  << std::chrono::duration_cast<std::chrono::nanoseconds>(_end_time - _start_time).count() << " nanos!" << std::endl;
    }
}

void write_file(const std::string &file_name, const int &loops)
{ 
    std::ofstream w_file (file_name,std::ofstream::app); 
    if (!w_file.is_open())
    {
        std::cout << get_time_now() << ",create or open " << file_name << " failed!" << std::endl;
        return;
    }

    char uuid_value[37];
    std::stringstream ss;
    static std::uint64_t num = 0;
    std::chrono::time_point<std::chrono::high_resolution_clock> _start_time, _end_time;
    for (int i = 0; i < loops; i++)
    {
        _start_time = std::chrono::high_resolution_clock::now();
        for (int j = 0; j < 1000000; j++)
        {
            srand(time(NULL));
            gen_uuid4(uuid_value, sizeof(uuid_value));
            ss << ++num << "," << uuid_value << std::endl;
        }
        _end_time = std::chrono::high_resolution_clock::now(); 
        w_file.write(ss.str().c_str(),ss.str().size());
        ss = std::stringstream();
        if (!w_file.good())
        {
            std::cout << get_time_now() << ", write failed!loops:" << i+1 << ",num:" << num << std::endl;
            break;
        }
        std::cout << get_time_now() << ",loops:" << i+1 << ",num:" << num << ",time cost:"
                  << std::chrono::duration_cast<std::chrono::seconds>(_end_time - _start_time).count() << " seconds,"
                  << std::chrono::duration_cast<std::chrono::milliseconds>(_end_time - _start_time).count() << " mills,"
                  << std::chrono::duration_cast<std::chrono::microseconds>(_end_time - _start_time).count() << " micros,"
                  << std::chrono::duration_cast<std::chrono::nanoseconds>(_end_time - _start_time).count() << " nanos!!!" << std::endl;
    }
    w_file.close();
    std::cout << get_time_now() << ",loops:" << loops << ",num:" << num << ",finished in " << __FUNCTION__ << std::endl;
}

int main(int agrs, char **argv)
{
    write_file(argv[1], atoi(argv[2]));
    return 0;
}

  

 

Compile

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

 

 

标签:std,now,end,random,start,time,cpp,include,generate
From: https://www.cnblogs.com/Fred1987/p/17565193.html

相关文章

  • mongodb从库无法启动一例(replication_recovery.cpp)
    环境:OS:centos7mongodb:4.4.22背景:1主1从1仲裁的环境,修改从库的集群ip后,执行如下操作后发现无法启动myrepl:PRIMARY>rs.remove("192.168.1.104:29001")myrepl:PRIMARY>conf=rs.conf()myrepl:PRIMARY>conf.members[1].host="192.168.1.107:29001"myrepl:PRIMARY>rs.r......
  • 题解 CF1842H【Tenzing and Random Real Numbers】
    看了题解。好难受,想用积分求概率,算了半天。发现没啥规律,不是不能算,就是太可怕了。Problem有\(n\)个\([0,1]\)范围内的均匀随机变量\(x_{1\cdotsn}\)和\(m\)条限制,每条限制形如\(x_i+x_j\le1\)或\(x_i+x_j\ge1\)。请你求出所有限制均满足的概率。对\(998244353\)......
  • cpp class constructor initialize list and override cout
    //book.h#pragmaonce#include<iostream>classbook{public:intidx;std::uint64_tid;std::stringauthor;std::stringcontent;std::stringcomment;std::stringisbn;std::stringsummary;std::stringtopic;boo......
  • LeetCode 519. Random Flip Matrix 哈希Map
    Thereisanmxnbinarygridmatrixwithallthevaluesset0initially.Designanalgorithmtorandomlypickanindex(i,j)wherematrix[i][j]==0andflipsitto1.Alltheindices(i,j)wherematrix[i][j]==0shouldbeequallylikelytobereturne......
  • 用googletest写cpp单测
    框架概述GoogleTest(也称为googletest)是由Google开发的C++单元测试框架。它的首个版本是在2004年发布的,作为Google内部的测试框架使用。随后,GoogleTest在开源社区中得到广泛应用,并在许多项目和组织中成为首选的C++单元测试框架。GoogleTest提供了丰富的断言函数和......
  • Math函数之Random随机数、Date日期
    publicstaticvoidmain(String[]args)throwsParseException{Datedate1=newDate();//nowDatedate2=newDate(0);//计算机元年Datedate3=newDate(Long.MAX_VALUE);//毫秒数Datedate4=newDate(Long.MIN_VALUE);......
  • 【HMS Core】AR Engine中,运行时出现../../../../src/main/cpp/world_ar_application.h
    ​【问题描述】1、AREngine中,从官网下载的“NDK示例代码”,运行时出现../../../../src/main/cpp/world_ar_application.h:30:10:fatalerror:'glm.hpp'filenotfound,该如何解决?2、arengine4.0.0.5版本新增秒放特性。不需要扫描平面,就能创建锚点并放置虚拟物体,目前只支持创......
  • SystemVerilog Dynamic Array Randomization
    https://verificationguide.com/systemverilog/systemverilog-dynamic-array-randomization/DynamicArrayRandomizeForadynamicarray,itispossibletorandomizebotharraysizeandarrayelements.randomizedynamicarraysizeInbelowexample,dynamicarr......
  • 使用whisper批量生成字幕(whisper.cpp)
    前言最近发现了whisper这个语音生成字幕的本地工具,但是whisper速度不算快,然后在github上发现了whisper.cpp这个项目,执行速度更快,还可以在命令行使用,这样就可以自己定制了。命令行压缩包下载命令行下载地址:https://github.com/Const-me/Whisper/releases下载【cli.zip】,解压即......
  • R语言代做编程辅导ASSIGNMENT FOUR - RANDOM GRAPHS(附答案)
    全文链接:https://tecdat.cn/?p=33183PROBLEM1)CreatingRandomAdjacencyMatricesScriptName:adjMatrixInput:n...Thenumberofverticesinthegraphp...Probablitytwoverticesareconnectedplot...whetherornotthematrixshouldbeplottedasagraph......