I have a c++ application, which contains large amount of std::cout. It runs on linux 2.6.x. I need to test the performance of the application, so i am thinking of redirecting the std::cout to /dev/null. In C, i could simply use dup2. Is there an equivalent in c++ to redirect std::ostream to a file or /dev/null?
3 Answers
The dup2 trick will still work in C++, since just like <stdio.h>, <iostream> is just a buffering layer atop the UNIX system calls.
You can also do this at the C++ level by disconnecting the buffer from std::cout:
std::cout.rdbuf( NULL ); Besides severing the relationship between std::cout and any actual output device, this will set the std::ios::badbit flag which will prevent any output conversions (e.g. numbers to text) from occuring. Performance should be much better than with the filesystem-level hack.
7 Comments
An alternative way would be to symlink your file to /dev/null.
% ln -s /dev/null core % ls -l core lrwx-xr-x 1 john users 9 Nov 18 12:26 core -> /dev/null To truly test your program speed however I would suggest to comment out the writes to your file and calculate the execution time difference, because writing to /dev/null might have different overhead than writing to a normal file.
dup2method from Potatoswatter works like a charm.