I wrote the following program in C++ to measure how much time it will take to print to the default output stream in different ways:
#include <algorithm>
#include <chrono>
#include <iostream>
using namespace std;
using namespace std::chrono;
int main() {
// Get starting timepoint
auto start = high_resolution_clock::now();
for (int i=0;i<100000;i++)
{
cout << "Hello";
}
// Get ending timepoint
auto stop = high_resolution_clock::now();
// Get duration. Substart timepoints to
// get durarion. To cast it to proper unit
// use duration cast method
auto duration = duration_cast<microseconds>(stop - start);
cout << "Time taken by function: "
<< duration.count() << " microseconds" << endl;
return 0;
}
At the first round I ran it with: cout << "Hello" << endl; and it took 147,570 microseconds.
At the second round I rant it with: cout << "Hello\n"; and took 128,543 microseconds.
Lastly, I ran it with: printf("Hello\n"); and it took 121,223 microseconds.
What caused this noticeable difference?
Note: I took the average from 10 tests for each one.
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);
Also 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.
Also as C++ is object-oriented , cin and cout are objects and hence the overall time is increased due to object binding.
So, a simple one liner, "std::ios_base::sync_with_stdio(false);" could make cin/cout faster than printf/scanf.
Hope this helps you
Anything in an OOP will be slower than the equivalent in a purely functional language like C. OOP comes with a price for object binding.
internal syncing / flushing in is what normally slows down iostream i/o in this case, Furthur, Actual times also vary from compiler to compiler.
Using scanf() in C++ programs is faster than using cin?
look at this answer for more clarity.
Related
#include <iostream>
#include <thread>
using namespace std;
int main()
{
for (int i = 0; i < 10000; i++) {
cout << "Hello\n";
}
this_thread::sleep_for(chrono::milliseconds(2000));
cout << "2 seconds have passed" << endl;
return 0;
}
In my code, I didn't call any std::flush or std::endl, but the hello's are printed before the 2 seconds delay. I am expecting to print all the hello's after the 2 seconds delay, but it didn't. My code runs like this:
Hello
Hello
.
.
.
Hello
Hello
(after 2 seconds)
2 seconds have passed
[terminated]
Why is this happening?
First of all, you're writing more output than a typical file buffer will hold, so you'd almost always expect at least some of the output to show up before the sleep.
Second, you're doing a lot of separate output calls, so if cout is unit-buffered, each one is going to be flushed immediately.
Third, you're writing a new-line at the end of each item, so if cout is line-buffered, (yup) each one is going to be flushed immediately.
So, if you want a better chance of seeing at least some of the output showing up after the sleep ends, turn off unit buffering and get rid of the new-lines:
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int main()
{
cout << nounitbuf;
for (int i = 0; i < 1000; i++) {
cout << "Hello";
}
// display something different to make it easier for user to see
// whether all output showed up before sleep or not.
cout << "...";
this_thread::sleep_for(chrono::milliseconds(2000));
cout << "2 seconds have passed" << endl;
return 0;
}
But even with this, there's no guarantee the behavior will change. Rather the contrary, most implementations go to some pain to assure that output written to the console shows up as promptly as possible, so even when you take steps toward delaying it, it'll still probably show up before the sleep. But this might improve your chances a little bit anyway.
I would like to make a very basic progress indicator by printing an 'X' char to cout every time a loop progresses another 10%. I am trying to do this as shown in the code pasted below, but it doesn't seem to be working - when really it seems it should.
It's supposed to display steady progress throughout the loop, but instead I get all the X's coming at once after the loop has finished. This is not because the loops are completed too quickly for me to perceive. To verify this you can add an extra 'F' to "TOTAL" to increase the duration of the looping substantially, and you'll see it's not just a question of perception.
Any ideas what might be causing this?
#include <iostream>
#define TOTAL 0xFFFFFFF
using namespace std;
int main(void) {
//Make a counter for counting loops
double counter = 0;
// Set it to trigger after each 10% of progress
double counterMax = TOTAL / 10;
cout << "Starting now..." << endl;
for (double i = 0; i < TOTAL; i++) {
// Do something... anything
i++;
i--;
// Increment the counter
counter++;
// Print an X when the counter exceeds the 10%
// trigger point, and then reset the counter.
if (counter > counterMax) {
cout << 'X';
counter = 0;
}
}
cout << endl << "Done!";
return 0;
}
System input/output calls are usually slow operations. To increase the efficiency of programs, input and output streams are often buffered, to reduce the number of calls to the operating system.
When a program needs "non-buffered" output, one solution is to use the buffered output functions, and simple "flush" the output to ensure the operating system processes any output which has been queued in any buffers.
When the output buffer is filled, or when the stream is closed, it is automatically flushed. The standard output is also automatically flushed by certain sequences, like endl. But you can trigger a flush of the standard output at any point by called cout.flush() or by using the flush manipulator, like:
cout << 'X' << flush;
I want some random characters to be printed to console and then deleted by "\b". After this I want to put my own variable so it will be looking like "randomizing". The problem is that it is happening too fast. I wanted to delay the output by using usleep or sleep function but when I'm using it, nothing is printed into console.
Short example:
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
char chars[]={'a','b','c','g','h','u','p','e','y'};
for(int i=0; i<8; i++)
{
cout << chars[i];
usleep(200000);
cout << "\b";
}
}
Problem is, std::cout is line-buffered. It stores all input in a buffer until a newline is encountered (or the program terminates). Use std::flush to flush std::cout explicitly:
cout << chars[i] << flush;
Notes:
since C++11, multithreading and time are standardized. That brings the std::this_thread:sleep_for function with it, which you should use for a portable >= C++11 program:
std::this_thread::sleep_for(std::chrono::milliseconds(200));
Try my little program slowtty from github.
It allows you to simulate in a pty the behaviour of an old rs232c line, by delaying the output per character as stty(1) command allows to set the baudrate.
You call it with
$ slowtty
$ stty 1200
$
and the terminal begins to write characters at a slow pace (like a 1200baud line)
On many systems output is buffered.
To ensure that what you sent out to cout has really been flushed out of buffers you need to call
cout.flush();
before the sleep
I know this is a noob question. I used this example code from here. How is it supposed to work? I thought you can input something for who but it just closes immediately.
#include <iostream>
#include "getopt_pp_standalone.h"
using namespace GetOpt;
using namespace std;
int main(int argc, char* argv[])
{
string who;
GetOpt_pp ops(argc, argv);
ops >> Option('n', "name", who, "world" ); /* the default name is 'world' */
cout << "Hello " << who << "!" << endl;
return 0;
}
Variants of getopt get options from the command line rather than input by a user.
You will need to run your program with something like:
myprog -n Pax
If you want interactive input from the user, get rid of the getopt stuff altogether and just use the streams, such as:
std::cout << "Identify yourself, interloper!\n";
std::cin >> who;
std::cout << "Hello, " << who << ", my name is Pax.\n";
A few other things to impart:
First, you may need to put a getchar() (or cin >> who) before the return if you're running in an IDE that closes the execution window instead of waiting. Otherwise, the output will go to the window and immediately disappear.
Second, while it's probably okay for small programs, using namespace std can cause problems with more substantial projects (in terms of polluting the standard namespace, see here for a good explanation). I prefer to fully qualify my calls, such as:
std::cout << "blah, blah, blah\n";
Third, endl is used far too often by most developers. Most times you should just either use '\n' instead, or just tack on \n to the end of a string like "Hello, world!\n". That's because the \n way doesn't force possibly inefficient flushing of the stream like endl does. That's covered here.
This program:
#include <iostream>
#include <cstdlib>
#include <string>
int main(int argc, const char *argv[])
{
using ::std::cerr;
using ::std::cout;
using ::std::endl;
if (argc < 2 || argc > 3) {
cerr << "Usage: " << argv[0] << " [<count>] <message>\n";
return 1;
}
unsigned long count = 10000;
if (argc > 2) {
char *endptr = 0;
count = ::std::strtoul(argv[1], &endptr, 10);
if ((argv[1][0] == '\0') || (*endptr != '\0')) {
cerr << "Usage: " << argv[0] << " [<count>] <message>\n";
return 1;
}
}
const ::std::string msg((argc < 3) ? argv[1] : argv[2]);
for (unsigned long i = 0; i < count; ++i) {
cout << i << ": " << msg << '\n';
}
return 0;
}
when timed like so:
$ time ./joe 10000000 fred >/dev/null
real 0m15.410s
user 0m10.551s
sys 0m0.166s
takes 15.4 seconds of real time to execute. Replace the output line with this: cout << i << ": " << msg << endl; and you end up with something like this:
$ time ./joe 10000000 fred >/dev/null
real 0m39.115s
user 0m16.482s
sys 0m15.803s
As you can see, the time to run more than doubles, and the program goes from spending minimal time in the OS to spending nearly half of it's time in the OS.
Both versions of the program have identical output, and are guaranteed by the standard to have identical output on every platform.
Given this, why do people persist in using endl as a synonym for '\n'?
Edit: In case it isn't obvious, this question is intended to be a leading question and is here for instructional purposes. I know why the performance penalty exists.
I'm not certain. Inserting std::endl into the output stream is defined as being equivalent to inserting .widen('\n') and then calling flush() and yet many programmers persist in using std::endl even when there is no cause to flush, for example they go on to immediately output something else.
My assumption is that it comes from an incorrect belief that it is somehow a more portable because it doesn't explicitly use a specific newline character. This is incorrect as \n must always be mapped to the system's correct newline sequence for non-binary files by the stream library.
Afaik, endl also flushes the stream, which may be the cause of the performance penalty.
Not everyone cares so much about performance. For some applications, guaranteeing the stream is flushed is much more important.
Edit: Also, I find endl easier to type than '\n' :-)
I tend to use endl with on stringstreams as it makes it easy to spot missing linebreaks.
My guess is that instructional texts use std::endl with the belief that it's simpler and less confusing for beginners, and afterward people got accustomed to using it.
The real question is, why did the compiler make such a dogs breakfast of compiling the endl version? If they're guaranteed to have the same semantics, then they should also have the same runtime.
Edit: obviously, I wasn't aware that endl flushed the stream... that's what you get for not looking it up.