Skip to content

Instantly share code, notes, and snippets.

@charmoniumQ
Last active May 31, 2021 18:31
Show Gist options
  • Save charmoniumQ/82453fe5afd07eca72d247be5d93d8f9 to your computer and use it in GitHub Desktop.
Save charmoniumQ/82453fe5afd07eca72d247be5d93d8f9 to your computer and use it in GitHub Desktop.
#define C_AND_POSIX_SHELL_POLYGLOT /*
# This section gets interpreted by the POSIX shell.
# It is inside a C comment, so it gets ignored by the C compiler.
CFLAGS="-pthread -lboost_thread -O3"
NIXPKGS=boost172
TARGET=/tmp/a.out
exec nix-shell \
--pure \
--packages clang_12 ${NIXPKGS} \
--command "echo Compiling && clang++ ${CFLAGS} ${0} -o ${TARGET} && echo Running && ${TARGET} ${@}"
# The exec ensures shell does not interpret beyond this point.
*/
#include <boost/thread.hpp>
#include <string>
#include <iostream>
#include <iomanip>
int main(int argc, const char* const* argv) {
if (argc != 2) {
std::cerr << "Usage: `" << argv[0] << " N`, where N is a positive integer" << std::endl;
return 1;
}
uint64_t iterations = std::stoi(std::string{argv[1]});
auto start = std::chrono::high_resolution_clock::now();
for (volatile uint64_t i = 0; i < iterations; ++i) {
boost::thread thread {[]{}};
thread.join();
}
auto stop = std::chrono::high_resolution_clock::now();
std::cout << std::setprecision(2) << double(std::chrono::duration_cast<std::chrono::microseconds>(stop - start).count()) / iterations << "us" << std::endl;
return 0;
}
/*
This is a self-contained C source file.
All you need to do is run this at the shell, and it will find its own
dependencies (through Nix), compile itself, and run itself.
Usage:
$ sudo apt install -y nix
$ chmod +x boost_thread_overhead.cpp
$
$ # first argument is how many trials to do
$ # It should take
$ ./bost_thread_overhead.cpp 65536
Compiling
Runing
25us
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment