'High CPU Usage for my own consolepplication client
I was building a console application which acts as a client. It connects to the given ip address of server. I am using Raknet in it. One of the problems i noticed is that the program Consoleapplicationxx.exe is taking high CPU usage (as shown by the Task Manager). 45% and more.
So i examined by code and found Raknet works in a while loop. Following is my code (not exact. from my memory)
int main(int argc, char** argv)
{
while(1)
{
for(packet->Receive();packet;packet->Deallocate(), packet->Receive()
{
switch(packet->data[0])
{
case xx:
break;
case yy:
break;
...
}
}
}
//some stuff and end
}
So i created another console application. Below is the code
#include <iostream>
#include <windows.h>
int main()
{
while (1)
{
}
}
When i run this program, it also uses high cpu. Then i added a Sleep(1000) inside the while loop and cpu usage reduced to 0%. i gradually reduced to sleep to 1 ms
#include <iostream>
#include <windows.h>
int main()
{
while (1)
{
Sleep(1);
}
}
And it works perfect(0% cpu usage). (Note: I tried putting Sleep(0) and it again high CPU usage 50%) So is this the way to solve this issue? So that i will add Sleep(1) to my original program?
I am planning to distribute the program after it is finished. So it is important to solve the issue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
