cin or printf?
Asked Answered
A

7

1

while working in c/c++,

1.cin/cout or 2.scanf/printf ,

which one of both , will have less execution or run time. OR both will have equal runtime.

my aim is to reduce the runtime of my code.

Antoniaantonie answered 23/8, 2010 at 20:16 Comment(17)
I agree with everyone about profiling, then making a decision. One advantage of using the C libraries (if you aren't using any of the rest of the C++ standard libraries) is that you might end up with smaller executables. This is sort of like a "C with classes" idiom.Ardoin
@Merlyn Morgan-Graham: If you are not using the rest of t6he C++ standard lib then you are using "C" so yes use scanf/printf as cin/cout are not available.Odious
There's no such thing as c/c++. Moreover cin and cout are not part of C.Murrumbidgee
@Martin,@Merlyn, aside from the considerations of standard-compliance and security (type-safety), the old C-stdio has one big advantage. It's most practical for many cases. Without this, nobody would care to use it in 2010. Try printf("%08d", i) in iostream.Liechtenstein
@rubber: See Boost.Format.Unshakable
@mahidce: "my aim is to reduce the runtime of my code." Why? What gave you the impression it's slow?Unshakable
@Martin: If you do what I mentioned, then you are not programming C, you are programming C++ without any of the standard C++ libraries. C++ isn't C + libraries =P But yes, as you mentioned, you would have to use scanf/printf.Ardoin
@Merlyn Morgan-Graham: Without the standard C++ libraries most things are not going to work so effecively you are using C. No exceptions no runtime type infortmation no new (so no constructor or destructor therefore no RAII) etc etc.Odious
@rubber boots: Yep iostreams are a lot more verbose. But that is mitigated by boost: #119598 std::cout << boost::format("%08d") % i;Odious
@Martin: So when I say "not including the standard C++ library", I'm not being very strict with my definition. Most people I've seen use the idiom aren't removing anything from the linker, they're just not including C++ headers. I have seen this approach have an impact on code size in my own projects. They may have been avoiding exceptions, but I don't really remember... It's been a while since I've tried to program in C++ on platforms where I'd get any benefit from this technique.Ardoin
@Martin: Along that spirit - codepad.org/VGnKFHmxArdoin
@Merlyn Morgan-Graham: That is just not going to save you anything. Including or not including header files will have zero affect on size (especially if you don't instanciate any objects).Odious
@Martin: Profile your comment ;) I have personally done so, and seen it have a large impact, although I would agree if you were to assert that there should be no impact w/ a good compiler (my example was a cross compiling GCC from 7 years ago). The biggest culprit was the iostreams library, which is what the OP is referring to. Ignoring that, you still get a lot of good language features even if you forego RAII and exceptions. Type safety, polymorphism, templates, references... Syntactic sugar can be extremely sweet.Ardoin
@Merlyn Morgan-Graham: assert that there should be no impact w/ a good compiler You mean every version of GCC since 3.0 (About 2001 or about 9 years ago) iostreams is in the c++ standard lib which is dynamically loaded and thus does not affect application size. You should also try it (where am I going wrong? codepad.org/gu2M9Roj)Odious
@Martin: I agree. If you're dynamically loading libraries, code size is pretty much never going to be effected by what you link. The experience I had was with statically linking (for an embedded device where the language runtime was more or less the OS of the device, as well). I tried out that scenario in VS2010, and I still get 49k for printf, and 130k for cout. I know I keep dodging your points by adding more information that I forgot to include before. I'll try to cut that out :)Ardoin
@Martin: The only point I have contention with is that C++ minus the libraries is the same as C. Other than that, YMMV for everyone, including the OP.Ardoin
GMan: Unless you can't use Boost of course :) Generally in small programs I prefer printf than dragging a lot of dependencies into it.Lipread
L
6

To bet on relative timings of console IO functions is imho without any real use. This is completely unpredictable (depends on environment). Console output depends completely on the speed of the console and usually not on the speed of the printf/cout. Try using local file output instead of console output.

Liechtenstein answered 23/8, 2010 at 20:18 Comment(1)
This is a very good point. Of course, with redirection any of cin, cout, scanf, printf could be doing file I/O.Kitchener
P
3

Performance Rule #1 - measure, then optimize

Before you try to figure out if cin/cout or scanf/printf will be faster, make sure you have measured and proved this is indeed the biggest performance issue with your application.

Prelect answered 23/8, 2010 at 20:18 Comment(0)
S
3

Since nobody has mentioned it yet, here comes a belated reply:
C++' IO streams are type-safe. When you want to print a double, the compiler finds out it's a double and inserts a call to the right overload of operator<<() at compile-time. With the C IO functions, OTOH, you have to specify the types manually, and thus can easily make errors that are only caught at run-time. (Just do std::printf("%d", 47.11) and you're deep in Undefined Behavior land.)

Oh yeah, that and: either of those two might easily keep up with the console. So write code that's easy to get right and easy to understand first. Then measure. And when you (somewhat surprisingly) found out this code is indeed the problem, see if it can be improved by changing. But only then.

Smoothspoken answered 23/8, 2010 at 21:0 Comment(0)
N
2

Early implementations of C++ iostreams tended to be noticeably slower than their C counterparts. That hasn't been the case for quite a while though. Unless you're using a relatively old compiler/library, chances are they're pretty close to the same speed overall (though if you measure, you may find that one is faster than the other in some specific circumstance or other -- I've certainly seen a few such).

Bottom line: if you want to improve performance much, this probably isn't one of the first places to look.

Nerval answered 23/8, 2010 at 20:24 Comment(1)
My experience has been that iostreams have a huge amount of overhead due to locale logic. Of course you should profile to find out what the hot spots are, but I wouldn't be at all surprised to learn that formatted I/O was dragging down performance.Kitchener
S
2

In my experience, the question is not of performance, but capability. cout and cin have applications that fprintf and fscanf are very difficult to use. However, formatting is often easier with fprintf than cout. Concentrate on robustness and correctness before profiling.

For performance, block I/O is faster than formatted I/O. For example:

#include <iostream>
#include <cstdio>

using namespace std; // Because I'm lazy right now. :-)

int main(void)
{
  static const char  some_text[] = "This is kinda long, but anything will do.\n";

  // The "fast" method using block writes:
  cout.write(some_text,
             sizeof(some_text) - sizeof('\0')); // Remove trailing nul from the length.

  // The slow method, using formatted write:
  cout << some_text;

  // Using the C language techniques:
  fwrite(some_text,
         sizeof(some_text) - sizeof('\0'),
         1,
         stdout);

  // Another fast method but slower than above:
  puts(some_text);

  // Finally, the slow method:
  fprintf(stdout, some_text);

  return 0;
}

When tuning a program's performance based on cout/cin vs. printf/scanf, one has to take into consideration that most of the time or bottleneck is not with the program but with the operating system. The operating system has a lot of overhead to manage when printing, such as resource management (is another task using the resource), switching contexts, etc. So if you want your program to run faster, use less I/O requests. If possible, combine several small requests into one large one.

Sulphurize answered 23/8, 2010 at 22:19 Comment(0)
L
1

Profiling is your friend; there's no one right answer, it depends on your specific usage pattern and platform.

Latticework answered 23/8, 2010 at 20:18 Comment(0)
B
1

Until you have profiled your code choosing one over the other amounts to nothing more than guessing. The best approach here is to pick the more usable function first. After later profiling reveals it to be a problem then switch to a provably faster function.

Butler answered 23/8, 2010 at 20:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.