Thread: CPU hog

  1. #1
    Registered User
    Join Date
    Dec 2004
    Location
    Mercer, PA
    Posts
    25

    CPU hog

    I have created a non blocking socket recv checker and keyboard checker. As you could imagain its using a loop to keep testing. But the problem is it bugs the CPU down majorly - how could I avoid this?
    Using windows XP, visual C++ 6 enterprise, winsock2.h, conio.h
    Thank you for your help!

  2. #2
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    My first thoughts are perhaps you are just running a loop that checks what is actually a blocking socket recv() instead of letting windows queue events in your program. My second thoughts are, may we see your code please?

  3. #3
    Registered User
    Join Date
    Dec 2004
    Location
    Mercer, PA
    Posts
    25
    haha sure - it might be a little strange. Its a small chat relay that I have devoloped. If you need more code let me know...
    Code:
    	while(recent != 1)
    	{
    		if(_kbhit())
    		{
    			sendbuf[sendx] = _getch();
    			cout << sendbuf[sendx];
    			if(sendbuf[sendx] == 13)
    			{
    				sendbuf[sendx+1] = '\0';
    				TBS += send(m_socket, sendbuf, strlen(sendbuf), 0);
    				for(x = 0; x < strlen(name); x++)
    				{
    					cout << name[x];
    				}
    				cout << ": ";
    				for(x = 0; x < (strlen(sendbuf) - 1); x++)
    				{
    					cout << sendbuf[x];
    				}
    				cout << endl;
    				sendx = -1;
    			}
    			sendx++;
    		}
    		//FD_ZERO(&ReadFDs);
    		FD_SET(m_socket, &ReadFDs);
    		if(select(0, &ReadFDs, 0, 0, &count) > 0)
    		{
    			if(FD_ISSET(m_socket, &ReadFDs))
    			{
    				TBR += bytesRecv = recv( m_socket, &recent, 1, 0 );
    				recvbuf[recvx] = recent;
    				if(recvbuf[recvx] == 13)
    				{
    					for(x = 0; x < 80; x++)
    						cout << '\b';
    					for(x = 0; x < strlen(cname); x++)
    					{
    						cout << cname[x];
    					}
    					cout << ": ";
    					recvbuf[recvx] = '\0';
    					for(x = 0; x < strlen(recvbuf); x++)
    					{
    						cout << recvbuf[x];
    					}
    					if(recvx + strlen(cname) + 2 < 80)
    					{
    						for(x = 0; x < 80 - recvx - strlen(cname) - 2; x++)
    							cout << " ";
    					}
    					for(x = 0; x < sendx; x++)
    						cout << sendbuf[x];
    
    					recvx = -1;
    				}
    				recvx++;
    			}
    			if(bytesRecv == SOCKET_ERROR)
    				break;
    		}
    	}
    how would you setup events in console programs?
    Last edited by multielements; 12-20-2004 at 10:58 AM.

  4. #4
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    One idea would be to add a sleep() function in your loop, and specify just a few milliseconds as the pause. It would slow down your program, but then so would any other option to stop using the CPU so much. Do a bit of research on the different options (there are many implementations of a pause function out there), and make sure you use one that uses the free time to give to other CPU uses. IIRC the windows.h version does that.

  5. #5
    Registered User
    Join Date
    Dec 2004
    Location
    Mercer, PA
    Posts
    25
    Yea I have seen many posts on this board saying to use the sleep() funciton. But I never really liked the idea of my program sleeping. Really I just want it to wait for certain incoming data without bashing my CPU. I mean windows is able to function without the CPU being used a lot.

  6. #6
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    >>to wait for certain incoming data without bashing my CPU
    Well then, specify a timeout other than 0 in select()

    Code:
    if(select(0, &ReadFDs, 0, 0, &count) > 0)
    {
    	if(FD_ISSET(m_socket, &ReadFDs))
    Just like to point out, since m_socket is the only socket in the FD_SET, as long as select() returns >0 then the socket that is readable will be m_socket. So the nested if is somewhat redundant in this case.
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  7. #7
    Registered User
    Join Date
    Dec 2004
    Location
    Mercer, PA
    Posts
    25
    Actually I had code like the for while - but then it slows down keyboard input time - haha.
    I'm such a problem aint I :-p.
    Ohh and the redundant FD_SET is necessary because if I hadnt set it - then FD_ISSET will ALWAYS return true - even if there is no data wait. I think that is what your are pointing out about my redundancy...

  8. #8
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    No I mean:
    Code:
    if(select(0, &ReadFDs, 0, 0, &count) > 0)
    {
       //do something with m_socket
    Since there is only 1 socket in the FD_SET, if m_socket is readable then select() will return 1; if m_socket is not readable, select() will return <1. So you don't need the if(FD_ISSET...) test at all in this particular case.

    >>but then it slows down keyboard input time
    Well then, that changes things a little doesn't it The only thing I can tell you, then, is Sleep() from <windows.h> or in your case <winsock2.h>, coupled with the nonstandard functions kbhit() or _kbhit() and getch(), will be your best bet. The Sleep() function (even specify just 1ms for the sleep duration) will take your CPU usage down from 100% to the 0-4% range, kbhit() lets you know when getch() won't block, so that you can keep updating if you receive a message.

    If you were writing this as a Windows application on the other hand, there would be a much nicer solution: Since all input/output/etc. goes through the message loop anyway, use asynchronous winsock with WSAAsyncSelect() and the world will be all hunky dory But in a console application there's no message loop, so that doesn't work for you.
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  9. #9
    Registered User
    Join Date
    Dec 2004
    Location
    Mercer, PA
    Posts
    25
    Ohh my goodness - it worked this time. Holy crap - last time I tried Sleep it did didily squat.
    Ill work on that select statement a lil - still a little confused - but if I reread it a few times it might sink in. Thanks a bunch! :-D

  10. #10
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    how would you setup events in console programs?
    You could do it manually, using loops and flags and constant 'if' statements, but judging by your current problem, I doubt that's the route you want to take. You could also use SDL. It's typically thought of as a media library for gaming, but it does event handling and a number of other jobs too. Check it out at www.libsdl.org

  11. #11
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    You could use something like this for maximum efficiency.
    Code:
    HANDLE hEvents[2];
    HANDLE hEvents[0] = CreateEvent(NULL, FALSE, FALSE, NULL);
    HANDLE hEvents[1] = GetStdHandle(STD_INPUT_HANDLE);
    WSAEventSelect(m_socket, hEvents[0], FD_READ);
    
    /* At this point hEvents[0] will be signalled when socket data is available
     * and hEvents[1] will be signalled when console input is available. */
    
    while (recent != -1)
    {
    	dwEvent = WaitForMultipleObjects(2, hEvents, FALSE, INFINITE);
    
    	if (dwEvent == WAIT_OBJECT_0)
    	{
    		// Socket data has arrived, call recv()...
    	}
    	else if (dwEvent == WAIT_OBJECT_0 + 1)
    	{
    		// Console input arrived...
    	}
    }

  12. #12
    Hardware Engineer
    Join Date
    Sep 2001
    Posts
    1,398

    Talking A bad analogy…

    But I never really liked the idea of my program sleeping.
    Do you keep your engine revved-up to redline all the time? ...when you’re at a stoplight? OK, a bad analogy, ‘cause your processor is running full-speed all the time (unless it’s in a power-save mode).

    But, you wouldn’t like it if Internet Explorer, or MS Word were sitting there doing nothing except taking CPU time away from your program.

    Note that this is only because we’re in a multitasking environment. Your program should play-nice with others. In a non-multitasking environment, you’re free to use the CPU however you wish. In fact, in simple (i.e. embedded) systems, you may not even have an operating system. In this case, your program is required to manage (i.e. hog) the CPU full-time!

  13. #13
    Registered User
    Join Date
    Dec 2004
    Location
    Mercer, PA
    Posts
    25
    Thats exactly what I needed! I was looking on the msdn library about that function but microsoft always makes things seem much more complicated with documentation. Blah. I understood the timeframe and I wanted to use INFINITE because it will just hang there waiting for input. Thank you so much!! :-D

  14. #14
    Registered User
    Join Date
    Dec 2004
    Location
    Mercer, PA
    Posts
    25
    Hey dougdbug that anology was very well put actually. I can see your point. I suppose that the CPU is always querying hardware and filling buffers. What I ment was when you look at the processor usage that windows gives it usually 0% (if your not doing anything) - but then again thats only saying usage from processes. Sorry my bad - I should have clarified what I was trying to say. :-p.
    Last edited by multielements; 12-20-2004 at 03:14 PM.

  15. #15
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    >>You could use something like this for maximum efficiency.
    Cool, I thought *maybe* something like that could be done, but figured it was just wishful thinking
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pthread question
    By quantt in forum Linux Programming
    Replies: 7
    Last Post: 04-07-2009, 01:21 AM
  2. questions on multiple thread programming
    By lehe in forum C Programming
    Replies: 11
    Last Post: 03-27-2009, 07:44 AM
  3. Upgrading my old CPU (for another old one!)
    By foxman in forum Tech Board
    Replies: 16
    Last Post: 01-11-2008, 05:41 PM
  4. Can you still view the bios screen with a bad CPU?
    By HyperCreep in forum Tech Board
    Replies: 4
    Last Post: 12-31-2006, 06:57 PM
  5. CPU temp
    By PING in forum Tech Board
    Replies: 5
    Last Post: 01-28-2006, 06:25 AM