Thread: Cout Question

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    39

    Cout Question

    Hi

    Bellow is an example of my help system im working on:-
    My question is the couts..Do they take up any cycles?

    e.g

    cout << "...........\n";
    cout << "...........\n";

    can also be written as:

    cout << ".........\n" << ".........\n";

    is the second one more efficent becuase it states less couts?

    Thank You For Your Help

    Alex

    Code:
    //C++ Help System Project
    #include <iostream>
    using namespace std;
    
    int main () {
    	char choice;
    	
    	for(;;) {
    	do {
    	cout << "Help On: \n";
    	cout << "  1. if\n";
    	cout << "  2. switch\n";
    	cout << "  3. for\n";
    	cout << "  4. while\n";
    	cout << "  5. do=while\n";
    	cout << "  6. break\n";
    	cout << "  7. continue\n";
    	cout << "  8. goto\n";
    	cout << "===================\n";
    	cout << "Choose One (q to quit): ";
    	cin >> choice;
    	} while( choice < '1' || choice > '8' && choice != 'q');
    	if(choice == 'q') break;

  2. #2
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    Quote Originally Posted by macman
    is the second one more efficent becuase it states less couts?
    That's a good question, and one I'd like to know the answer to as well. I tend to think yes, but that's just an instinct. If you like the couts just because they keep the spacing nice and neat, remember that C++ ignores whitespace. Also, you might want to add a flush call at the end of all that so that you know your output has been written.
    Code:
    //C++ Help System Project
    #include <iostream>
    using namespace std;
    
    int main () {
    	char choice;
    	
    	for(;;) {
    	do {
    	cout << "Help On: \n"
    	     << "  1. if\n"
    	     << "  2. switch\n"
    	     << "  3. for\n"
    	     << "  4. while\n"
    	     << "  5. do=while\n"
    	     << "  6. break\n"
    	     << "  7. continue\n"
    	     << "  8. goto\n"
    	     << "===================\n"
    	     << "Choose One (q to quit): " << flush;
    	cin >> choice;
    	} while( choice < '1' || choice > '8' && choice != 'q');
    	if(choice == 'q') break;
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    If it is, it won't be by any significant amount. Maybe a few CPU cycles for the function call, and then anything that gets executed no matter what whenever cout is called.

    Think about the trade-off between reader-friendly code and CPU efficiency. Unless you're programming for really time-critical situations, err on the side of reader-friendliness.

  4. #4
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    I would agree with sean - if you're looking to optomize your code from the output standpoint, you'll notice that the less you have to output the faster your program runs. it really doesn't matter how you output it (in your case), just how much you output... for example, consider this code:
    Code:
    #include<iostream>
    #include<fstream>
    #include<ctime>
    
    int main()
    {
        time_t start=clock();
        
        char ch;
        std::fstream file("Untitled1.dat",std::ios::in|std::ios::binary);
        
        while(file.get(ch))
        {
            std::cout<<ch;
        }
        
        file.close();
        time_t stop=clock();
        std::cout<<"\n----------\nTime: "<<stop-start<<"\n----------"<<std::endl;
        std::cin.get();
        return 0;
    }
    as it is, it took about 375 miliseconds to run on my machine... but if I comment out the cout in the loop, it only takes about 16. my file was 20 paragraphs of lorem ipsum.


    edit: it seems as if the only thing that really makes much of a difference is as how much you use either cout or operator <<. for examle, see the code below - each commented block has the time it took to run it uncommented:
    Code:
    #include<iostream>
    #include<fstream>
    #include<ctime>
    
    int main()
    {
        time_t start=clock();
        
        for(register short int i=0;i<1000;i++)
        {
            /* 171 miliseconds
            std::cout<<"1";
            std::cout<<"2";
            std::cout<<"3";
            std::cout<<"4";
            std::cout<<"5";
            */
            
            /* 156 miliseconds
            std::cout<<"1"<<"2"<<"3"<<"4"<<"5";
            */
            
            /* 62 miliseconds
            std::cout<<"12345";
            */
        }
    
        time_t stop=clock();
        std::cout<<"\n----------\nTime: "<<stop-start<<"\n----------"<<std::endl;
        std::cin.get();
        return 0;
    }

    edit2: I was kidding about the milisecond thing... clock() returns processor time...
    Last edited by major_small; 04-07-2005 at 10:37 AM.
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    847
    They are both the same. << and >> are the shift left and shift right operators, the reason they work with the cin and cout classes is because of operator overloading.
    An overloaded operator function is declared like this
    Code:
    <return type> operator << (<arg type>);
    so each time you use an operator with a class you are calling a member function of that class.

  6. #6
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >is the second one more efficent becuase it states less couts?
    Performance shouldn't be your primary concern because the time it takes to call a function pales in comparison to a device write. When you're doing I/O, no amount of micro-optimization will make a difference.
    My best code is written with the delete key.

  7. #7
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    I always figured that was how it went, but I never tested it until just now
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  8. #8
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Quote Originally Posted by Quantum1024
    << and >> are the shift left and shift right operators,

    When talking about cout and cin they are referred to as the stream insertion and extraction operators.

    Like Quantum1024 and sean_mackrory said, each use of the stream insertion operator << resolves into a new call to the overloaded cout.operator<<() function. The first use calls the function and returns a reference to the stream which can then be chained to another call to the cout.operator<<() function for second and subsequent insertions in the same line of code. If you really want to shave every possible cycle off of that output, I would suggest simply:

    Code:
    cout << ".........\n.........\n";
    That resolves into just a single function call and would therefore be the quickest. But it probably wouldn't do that much good in reality.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  9. #9
    Registered User Scribbler's Avatar
    Join Date
    Sep 2004
    Location
    Aurora CO
    Posts
    266
    << evaluates from left to right and returns a reference to its left operand. So basically...
    Code:
    cout << "..........\n" << "..........\n"
    Would just evaluate to
    Code:
    cout << "..........\n..........\n"
    wouldn't it?
    Last edited by Scribbler; 04-07-2005 at 11:33 AM.

  10. #10
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    Quote Originally Posted by Scribbler
    << evaluates from left to right and returns a reference to its left operand. So basically...
    Code:
    cout << "..........\n" << "..........\n"
    Would just evaluate to
    Code:
    cout << "..........\n..........\n"
    that may be true, but what about the extra cycles used to make that evaulation? see my timed code above
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  11. #11
    Registered User
    Join Date
    Mar 2005
    Posts
    39
    Thanx For your replys everybody!

    I think that Ill keep it as it is..Like you guys say..it would really be much of a cycle cut...and keeping the code nice and user friendly is a habbit i want to fall in!

    The flush statement show second post down..what exactly does it do?

    Im not sure what u mean by:-

    Also, you might want to add a flush call at the end of all that so that you know your output has been written.
    Code:
    Cheers
    Alex

  12. #12
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >The flush statement show second post down..what exactly does it do?
    It causes and buffered characters to be written to the device.

    >Im not sure what u mean by
    In C, it's prudent to flush the output stream when you want interactive input because, due to buffering, the request for input may precede the prompt:
    Code:
    printf ( "Enter a string: " ); /* May not be shown first */
    fgets ( s, sizeof s, stdin );
    To be more correct, an explicit flush of the stream is required:
    Code:
    printf ( "Enter a string: " ); /* Guaranteed to be shown first */
    fflush ( stdout );
    fgets ( s, sizeof s, stdin );
    In C++ this issue is mostly academic because cout is tied to cin. When you request input from cin, cout is automatically flushed.
    My best code is written with the delete key.

  13. #13
    Registered User
    Join Date
    Mar 2005
    Posts
    39
    So basically..

    using the flush..is "old school?"
    Is there anyneed for it at all?..or is just left over from c?

    ..ahhhh..wait
    so where theres no cin..then i should flush?

    Cheers For The Info!

    Alex

  14. #14
    Tropical Coder Darryl's Avatar
    Join Date
    Mar 2005
    Location
    Cayman Islands
    Posts
    503
    Quote Originally Posted by major_small
    that may be true, but what about the extra cycles used to make that evaulation? see my timed code above
    If that evaluation is made, it would be at compile time and not at runtime.

  15. #15
    Registered User
    Join Date
    Dec 2004
    Location
    UK
    Posts
    109
    From my understainding cin and cout are just references to objects, the function call occurs when eveluating << or >> (both of which take a stream object as their left operand and return a reference to it).

    Which should mean that
    Code:
    cout << "something";
    cout << "something";
    and

    Code:
    cout << "something" << "something";
    should execute in exactly the same time (note that the output occurs when << is executed, cout is not a function)

    Code:
    cout << "somethingsomething";
    should take a bit less since it only requires one output operation.
    But as Prelude said it is all irrelevant considering how long output takes anyway.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. another do while question
    By kbpsu in forum C++ Programming
    Replies: 3
    Last Post: 03-23-2009, 12:14 PM
  2. Question about cout an stack object?
    By joenching in forum C++ Programming
    Replies: 8
    Last Post: 05-08-2005, 10:10 PM
  3. Question type program for beginners
    By Kirdra in forum C++ Programming
    Replies: 7
    Last Post: 09-15-2002, 05:10 AM
  4. cout question
    By The Gweech in forum C++ Programming
    Replies: 4
    Last Post: 07-09-2002, 04:11 PM
  5. cout question...
    By bishop_74 in forum C++ Programming
    Replies: 1
    Last Post: 12-06-2001, 11:22 AM