项⽬中需要将原有的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 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 return boost::lexical_cast 使⽤⾃⼰的随机种⼦,适当的降低了⽣成uuid的质量,最后测下来⽣成uuid的速度⼤概在 60000/s,还可以接受。 我另外还尝试了uuid-dev,⾸先安装库: apt-get install uuid-dev 测试代码: #include 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 std::cout<