Skip to content

Instantly share code, notes, and snippets.

@azat
Last active January 25, 2024 21:35
Show Gist options
  • Save azat/ddc313240e72672166ffd6dcccede773 to your computer and use it in GitHub Desktop.
Save azat/ddc313240e72672166ffd6dcccede773 to your computer and use it in GitHub Desktop.
test pthread_create
#include <cstdint>
#include <ctime>
#include <iostream>
#include <sys/types.h>
#include <thread>
#include <list>
uint64_t now_ns()
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
return ts.tv_sec * (uint64_t)1e9 + ts.tv_nsec;
}
template <class F>
uint64_t elapsed(const F & f)
{
uint64_t start = now_ns();
f();
uint64_t end = now_ns();
return end - start;
}
int main()
{
std::list<std::thread> threads;
{
uint64_t create_took = elapsed([&]() {
for (int i = 0; i < 30e3; ++i)
{
try
{
threads.emplace_back([]() {});
}
catch (...)
{
std::cerr << "Cannot create thread " << i << ". Breaking\n";
break;
}
}
});
std::cerr << "join: took " << create_took/1e6 << "ms, rate: " << threads.size()/((double)create_took/1e9) << " TPS\n";
}
{
uint64_t join_took = elapsed([&]() {
for (auto & thread : threads)
thread.join();
});
std::cerr << "join: took " << join_took/1e6 << "ms, rate: " << threads.size()/((double)join_took/1e9) << " TPS\n";
}
}
$ clang++ /tmp/test-threads.cpp -o /tmp/test-threads -O3 && time /tmp/test-threads
join: took 592.951ms, rate: 50594.4 TPS
join: took 136.108ms, rate: 220414 TPS
real 0m0.734s
user 0m0.054s
sys 0m0.678s
$ clang++ /tmp/test-threads.cpp -o /tmp/test-threads -O3 && time /tmp/test-threads
join: took 582.641ms, rate: 51489.7 TPS
detach: took 135.038ms, rate: 222160 TPS
real 0m0.722s
user 0m0.068s
sys 0m0.654s
#include <thread>
int main()
{
for (int i = 0; i < 50e3; ++i) {
std::thread t([]() {});
t.join();
}
}
$ clang++ /tmp/test-threads.cpp -o /tmp/test-threads -O3 && time /tmp/test-threads
real 0m1.201s
user 0m0.079s
sys 0m0.723s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment