您的当前位置:首页正文

UUIDperformance生成uuid的性能问题

2023-01-16 来源:爱go旅游网
UUIDperformance⽣成uuid的性能问题

项⽬中需要将原有的id统⼀改为uuid,于是直接⽤boost中的uuid库来⽣成uuid。

但在测试中发现程序性能严重下降,原来每分钟能处理60万条数据,使⽤uuid后只能处理2万条左右。于是跟踪之,先看我们的实现⽅式:

1 static std::string uuid()2 {

3 boost::uuids::uuid uuid = boost::uuids::random_generator()();4 return boost::lexical_cast(uuid);5 }

6

实测下来,⽣成uuid的速度⼤概在1000/s,这太低效了!

google之,发现问题可能在于⽣成uuid时的随机种⼦:

The requirement for uuid::create to be fast conflicts with the requirement that it needs to create a \"universally unique identifierhat is, a high-quality random number. Typically, high-quality randomness is more important than performance, as one rarelyneeds to create one million UUIDs. One could argue that the high-performance case is adequately addressed by the engine-taking overload.

最后同事改成了这样:

static std::string uuid(){

static time_t t = time(NULL); boost::mt19937 ran; ran.seed(t++);

boost::uuids::basic_random_generator gen(&ran); boost::uuids::uuid u = gen();

return boost::lexical_cast(u);}

使⽤⾃⼰的随机种⼦,适当的降低了⽣成uuid的质量,最后测下来⽣成uuid的速度⼤概在 60000/s,还可以接受。

我另外还尝试了uuid-dev,⾸先安装库:

apt-get install uuid-dev

测试代码:

#include #include #include using namespace std;

typedef struct _GUID{

unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8];} GUID, UUID;

std::string GuidToString(const GUID &guid){

char buf[64] = {0}; snprintf( buf,

sizeof(buf),

\"{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}\", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]); return std::string(buf);}

int main(int argc, void** argv){

GUID guid;

time_t t = time(NULL); for(int i=0; i<1000000; i++) {

uuid_generate(reinterpret_cast(&guid)); }

std::cout<g++ -o test test.cpp -luuid测试结果为20万/秒,更快了呵。

-------------------------------------------------------------------------update:

在多线程环境下,boost⽣成的uuid会重复,推测可能是随机种⼦不可重⼊造成的,也没有深究。最后还是使⽤uuid-dev了,实测多线程⽆此问题。

因篇幅问题不能全部显示,请点此查看更多更全内容