Skip to content

Instantly share code, notes, and snippets.

@false-git
Last active May 14, 2023 02:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save false-git/263ae0e4ea00ed8832244b98c7b4a563 to your computer and use it in GitHub Desktop.
Save false-git/263ae0e4ea00ed8832244b98c7b4a563 to your computer and use it in GitHub Desktop.
UUIDの衝突が起きるかテストするプログラム
// c++ -std=c++20 -O2 uuid_test.cc
#include <chrono>
#include <iostream>
#include <thread>
#include <mutex>
#include <set>
#include <vector>
#include <uuid/uuid.h>
struct Uuid {
uuid_t uuid;
Uuid() = default;
Uuid(const Uuid &other) { uuid_copy(uuid, other.uuid); }
Uuid(const uuid_t other_uuid) { uuid_copy(uuid, other_uuid); }
void generateInplace() { uuid_generate(uuid); }
static Uuid generate() { Uuid wrapped; uuid_generate(wrapped.uuid); return wrapped; }
bool operator<(const Uuid &other) const { return uuid_compare(uuid, other.uuid) < 0; }
bool operator==(const Uuid &other) const { return uuid_compare(uuid, other.uuid) == 0; }
};
std::mutex mutex;
std::set<Uuid> set;
std::chrono::system_clock::time_point start;
std::chrono::system_clock::time_point previous;
size_t count = 0;
void gen(int id) {
while (true) {
uuid_t u1;
uuid_generate(u1);
std::lock_guard<std::mutex> lock(mutex);
if (set.find(u1) != set.end()) {
uuid_string_t u1str;
uuid_unparse(u1, u1str);
auto now = std::chrono::system_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(start - previous).count();
std::cout << id << ":" << count << "," << elapsed << "," << set.size() << "," << u1str << std::endl;
exit(1);
}
set.insert(u1);
auto size = set.size();
if (size % 1000000 == 0) {
count += 1;
auto now = std::chrono::system_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(now - previous).count();
if (elapsed > 5) {
std::cout << id << ":" << count << "," << elapsed << "," << size << ",reset" << std::endl;
set.clear();
now = std::chrono::system_clock::now();
} else {
std::cout << id << ":" << count << "," << elapsed << "," << size << std::endl;
}
previous = now;
}
}
}
int main(int argc, char *argv[])
{
std::vector<std::thread> threads;
previous = start = std::chrono::system_clock::now();
for (int i = 0; i < 8; i++) {
threads.push_back(std::thread(gen, i));
}
// 返ってこないからここから先は不要
for (auto &t : threads) {
t.join();
}
return 0;
}
@false-git
Copy link
Author

オンメモリだとsetのサイズが3億あたりでだいぶ遅くなるので、100万個生成するのに5秒よりかかるようになったらsetをクリアしてやり直すように修正。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment