PDA

View Full Version : c++



michiel-reenaers
November 14th, 2013, 08:41 PM
I'm beginning with c++ (only 2 days)

Does anyone know how you can make a script (that has a infinit loop) that checks the last line of a file continuously, Less resource unfriendly?

Right now I just have a while loop that is continuously true, that then reads the last line, and does some calculations.

But as you can guess that isn't so great for my cpu.

this is the main of my code:

int main() {

int q = 0;
do {
// RESET //
memcpy ( SAVEDSENTENCE, COMPLETESENTENCE, strlen(COMPLETESENTENCE)+1 );
memset(COMPLETESENTENCE, '\0', sizeof(COMPLETESENTENCE));
memset(SENTENCE, '\0', sizeof(SENTENCE));
memset(FUNCTIONNUMBER, '\0', sizeof(FUNCTIONNUMBER));
memset(THIRDVARIABLE, '\0', sizeof(THIRDVARIABLE));
//


// SETVARIABLES //
GetSentence();

//Check if this sentence matches previous sentence
if (memcmp(SAVEDSENTENCE, COMPLETESENTENCE, sizeof(SAVEDSENTENCE))== 0)
{
FUNCTIONNUMBER[0]='9';
}

switch (atoi(FUNCTIONNUMBER))
{
case 0: Result();
break;
case 1: LoadingDots();
break;
case 2: UserInputResult();
break;
case 3: ChangeColor();
break;
}
double timeInterval;
for ( timeInterval = 0; timeInterval <= 900000000; timeInterval++);
}
while (q == 0);
}

I compile with g++ (should that make a difference).
Feel free to give some other tips on making the code less resource demanding.

TheFu
November 14th, 2013, 11:24 PM
That wheel exists already.
tail -f /path-to-log-file
You can find the source code for tail on the internet. I bet it is C.

BTW, memset/memcpy/memcmp are not the normal C++ method for doing that sort of stuff. I've never used those functions in any program .... ever. and please wrap the code in "code" tags with proper indentation.

r-senior
November 16th, 2013, 11:26 AM
double timeInterval;
for ( timeInterval = 0; timeInterval <= 900000000; timeInterval++);


This is what is killing your CPU. You are spinning in a loop to create a time delay. The way to do it is to use sleep, which tells the operating system you don't want to do anything for a time.


#include <iostream>

using namespace std;

int main()
{
for (int i = 0; i < 10; ++i) {
cout << "Hello" << endl;
sleep(1);
}
}


To compile:


g++ -o sleepy sleepy.cc