Timing

Timing

// glog 0.09 ms
LOG(INFO) << "test";   // 0.09 ms

// steady_clock 0.000068 ms
static std::chrono::steady_clock::time_point tic = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point toc = std::chrono::steady_clock::now();
auto time_elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(toc - tic);
double time_ms = time_elapsed.count() / 1000000.0;
tic = toc;

// std::hash  0.000050 ms (avg from 10 times)
auto result = std::hash<std::string>{}("centroid start");

// map index  0.000100 ms
std::unordered_map<std::string, double> value;
value["test"];

// get filename 0.001 ms
std::cout << __FILE__ << "\n";

// get line number 0.004 ms
std::cout << __LINE__ << "\n";

// cout  0.0014 ms
std::cout << "[TIMING] " << note << ": " << time_ms << " ms" << std::endl;

// printf  0.0013 ms  // using printf with std::string is not recommended
printf("[TIMING] %s: %f ms\n", note.c_str(), time_ms);

// cin  0.025 ms  (with sync disabled 0.015 ms)
std::cin >> test;

// scanf 0.018 ms
scanf("%s", &test);

Tricks to run cin/cout faster

  • By default, cin/cout waste time synchronizing themselves with the C library’s stdio buffers, so that you can freely intermix calls to scanf/printf with operations on cin/cout. Turn this off with std::ios_base::sync_with_stdio(false);.

  • Many C++ tutorials tell you to write cout << endl instead of cout << '\n'. But endl is actually slower because it forces a flush, which is usually unnecessary. (You’d need to flush if you were writing, say, an interactive progress bar, but not when writing a million lines of data.) Write '\n' instead of endl.

  • There was a bug in very old versions of GCC (pre-2004) that significantly slowed down C++ iostreams. Don’t use ancient compilers.

Avoid these pitfalls, and cin/cout will be just as fast as scanf/printf. Some benchmarks indicate that cin/cout is actually 5%–10% faster. This is probably because scanf/printf need to interpret their format string argument at runtime.

However, I used to have a problem Maximum Identity Matrix on CodeForces that only scanf can pass but not cin (with sync disabled already; exactly the same code elsewhere).

References

Loop Timer

Last updated

Was this helpful?