C++: Tools – code examples
Measuring runtime
Tools#chrono#time#benchmark
Use case: Check how long a piece of code takes (profiling, benchmarks).
#include <chrono>
#include <iostream>
int main() {
auto start = std::chrono::steady_clock::now();
long long summe = 0;
for (int i = 0; i < 100'000'000; ++i) summe += i;
auto ende = std::chrono::steady_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(ende - start).count();
std::cout << summe << " in " << ms << " ms\n";
}steady_clock is monotonic (ideal for measurements). The result summe is printed so that the optimizer does not throw the loop away. Always measure with -O2.
Random numbers
Tools#random#mt19937#randomness
Use case: Generate dice rolls, test data, simulations or samples.
#include <iostream>
#include <random>
int main() {
std::mt19937 gen(std::random_device{}());
std::uniform_int_distribution<int> wuerfel(1, 6);
for (int i = 0; i < 5; ++i) std::cout << wuerfel(gen) << ' ';
std::cout << '\n';
}mt19937 is the random number generator, random_device provides the seed, and the distribution maps to the number range. You avoid C's rand().
Command-line arguments
Tools#argc#argv#cli#main
Use case: Build your own CLI tools that accept parameters.
#include <iostream>
#include <string>
#include <vector>
int main(int argc, char* argv[]) {
std::vector<std::string> args(argv + 1, argv + argc);
if (args.empty()) {
std::cerr << "Usage: " << argv[0] << " <name>\n";
return 1;
}
std::cout << "Hello " << args[0] << '\n';
}argv[0] is the program name, argc the number of arguments. The vector args makes the raw data (char*) conveniently usable as std::string. Call it e.g. as ./tool Ada.