Program slows the computer down a lot.

Started by
9 comments, last by nprz 18 years, 4 months ago
Hey^^ I wrote a simple little program that will change the desktop background at desginated times of the day. It works fine, but when i run it the computer slows down a lot. I'm sure it's the fact that i'm not the best coder in the world, so i'm sure this program could use a TON of optimizations >.> Anyway, i was hoping someone could look over it, and possibly suggest some ideas on how to make it less intensive? I've commented it pretty well, so hopeflly it won't be too hard to read over. Also, the main purpose is to change the background at set times of the day. You can also ahve different "day cycles" which means that every day it will be on a different cycle of pictures. If you have 2 day cycles, every other day will be the same cycle, and each day inbetween will be different. If you have any questions about any section of code, just ask^^ here it all is: Desktop.cpp ------------------

#include <cstdlib>
#include <Windows.h>
#include <fstream>
#include <string>
#include <cmath>
#include <ctime>

using namespace std;

// Open the Options file for global use.
static fstream File("myfile.txt", ios::in);

//////////////////////////////////////////////////////////////////////////////////////
// Name: StrtoInt
// Does: Turns a string of digits into a mathematically manipulatable integer.
// Take: string
// Rtrn: int
//////////////////////////////////////////////////////////////////////////////////////
int StrtoInt(string NumString)
{
	double Num = 0;               // The integer form of our string.
	int StrLen = NumString.length();   // The srings length
	
	// While the string still contains characters...
	while(StrLen--)
	{
		char OneDigit = NumString[0];            // Pull out the front most character.
		NumString = NumString.substr(1, StrLen); // Then chop it off of the string.
		
		// Put that digit through a switch statment...
		switch(OneDigit)
		{
            // ... and for each possible digit, add it to our Num variable.
            // Making sure to multiple it by a power of ten, to ensure
            // that it stays in the slot it's supposed to.
			case '1':
				Num += 1*pow((double)10, (double)StrLen);
				break;
			case '2':
				Num += 2*pow((double)10, (double)StrLen);
				break;
			case '3':
				Num += 3*pow((double)10, (double)StrLen);
				break;
			case '4':
				Num += 4*pow((double)10, (double)StrLen);
				break;  
			case '5':
				Num += 5*pow((double)10, (double)StrLen);
				break;  
			case '6':
				Num += 6*pow((double)10, (double)StrLen);
				break;  
			case '7':
				Num += 7*pow((double)10, (double)StrLen);
				break;  
			case '8':
				Num += 8*pow((double)10, (double)StrLen);
				break;  
			case '9':
				Num += 9*pow((double)10, (double)StrLen);
				break;  
			case '0':
				Num += 0;  //0*pow(10, x+1)
				break;
			default:
				Num *= -10000; //If an error occurs, Num will be some obscure negative number.
				break;
				
		}
	}
	
	// Return an Integer form of our number.
	return (int)Num;
}

//////////////////////////////////////////////////////////////////////////////////////
// Name: GetDays
// Does: Gets the total number of day cycles from the options file.
// Take:
// Rtrn: int
//////////////////////////////////////////////////////////////////////////////////////
int GetDays()
{
	int TotalDays = 0;   // the total day cycles.
	string Finder;       // A file searching string.
	
	// Dig through the file until we hit the end of the file.
	// for each "Day" we come across on the way, incriment TotalDays.
	while(!File.eof())
	{
		File >> Finder;
		if(Finder == "Day") TotalDays++;
	}
	
	// Reset the File stream, and return the total number of day cycles found.
	File.clear();
	File.seekg(0, ios::beg);
	
	return TotalDays;
}

//////////////////////////////////////////////////////////////////////////////////////
// Name: CheckTimes
// Does: Compares the current time to all of the listed times in the options file,
//       if there is a match, it returns the picture location for that time,
//       if not, it returns "No Change". 
// Take: int, string
// Rtrn: string
//////////////////////////////////////////////////////////////////////////////////////
string CheckTimes(int WhatDay, string ClockTime)
{
	string Finder;       // A file searching string.
	string Picture;      // The picture file path.
	string PictureTime;  // The time to change to the Picture.
	
	
	// This will dig through the file untill it gets to the correct day cycle.
	// it basicly just skips through each instance of the word "Day" until
	// it has goten to the current day cycle.
	while(WhatDay--)
	{
		while(Finder != "Day")
		{
			File >> Finder;
		}
		Finder = "";
	}
	
	// Now, with the cursor at the correct day cycle, we start looking at times
    // within that day cycle.
    // It stops looking once it hits the end of the file, or runs into the next day cycle.	
	while(Finder != "Day" && !File.eof())
	{
		File >> Finder;
		
		// Are we at a picture path?
		if(Finder == "Picture:")
		{
            // set that picture path to the Picture variable.
			File >> Picture;
			File >> Finder;
		}
		
		// Are we at a time designation?
		if(Finder == "Time:")
		{
            // set that time to the PictureTime variable.
			File >> PictureTime;
			PictureTime += ":00"; // add a ":00" on the end so that the background doesn't
			                      // constantly set for an entire minute.
		}
		
		// If the current time is equal to the PictureTime, then reset the File
		// stream and return that pictures path.
		if(PictureTime == ClockTime)
		{
			File.clear();
			File.seekg(0, ios::beg);
			return Picture;
		}
	}
	
	// If no picture was found to match the current time, reset the File stream
	// and return "No Change".
	File.clear();
	File.seekg(0, ios::beg);
	
	return "No Change";
}


  /////////////////////////////////////////////////////////////
 //                     The Main Function                   //
/////////////////////////////////////////////////////////////
int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nFunsterStil)
{
	while(1)
	{
        // Set the current time.
		time_t CurTime = time(0);
		
		// Turn the Current time into a string.
		string TimeStr = asctime(localtime(&CurTime));
		
		// Set the Date from a portion of the Time string.
		string Date = TimeStr.substr(8, 2);
		
		// Set the Time in Hour:Minute:Second form from the Time string.
		string ClockTime = TimeStr.substr(11, 8);
		
		// Modulus the Current date by the total number of Day cycles.
		int ModDate = (StrtoInt(Date) % GetDays()) +1;
		
		// Get the background image. If no change is needed, will be set to "No Change".
		string BackImage = CheckTimes(ModDate, ClockTime);
		
		// If the background image needs to be changed, change it.
		if(BackImage != "No Change")
			SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (void*)BackImage.c_str(), SPIF_UPDATEINIFILE);
	}
}




--------------------------- myfile.txt ---------------------------

Day 1
Picture: C:\Main\Desktop\misc-lonelysky.bmp
Time:    03:00

Picture: C:\Main\Desktop\girl_g11.bmp
Time:    11:00

Picture: C:\Main\Desktop\redcross.bmp
Time:    18:00

Picture: C:\Main\Desktop\misc-ladyofthelake.bmp
Time:    23:00




---------------------------- Meow. [Edited by - KuroKitten on December 19, 2005 4:17:22 PM]
Advertisement
You need a Sleep function...

I would also recommend having it sleep for maybe a minute, and determine if that current time is within a minute of the time required in your file.
Try adding in

/* for checks at 1 second intervals. you can increase it if you want, if you don't need 1 second accuracy. i'd probably recommend once a minute (60000) or so.
*/
Sleep(1000);

after

if(BackImage != "No Change")
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (void*)BackImage.c_str(), SPIF_UPDATEINIFILE);


That will stop the program from just stealing all of the cpu.

Edited: Bah! Beaten to it! =)
Well the reason that this slows the computer down alot is that you are giving NO time to other applications, its running all the time, which is highly unnessisary for a program that runs in the back ground. You can free some % of comp use (thats not memory that attention) by using the sleep function bulit into windows.

just adding the following line Sleep(10000); to the end of the code should give you a noticable diffrence. (the number is the amount of miliseconds to pause. You can play with this number a bit in order to get it to work as you like

BTW use "
 
" tags next time you post large amounts of code

hope i helped

|^ beaten to it
____________________________"This just in, 9 out of 10 americans agree that 1 out of 10 americans will disagree with the other 9"- Colin Mochrie
Oh, wow, that's a really cool function O.O hat should help a lot. As it is in the code anyway, it only updates perminute. If I just do a single check every minute that should speed up things a ton^^

Also, how exactly should I use those tags? do i jsut quote whatver the title is? eg. "Program slows the computer down a lot."? It would be nice to warn about those things.
[ source ]

[ /source ]

without the spaces... Those are the tags you should put around your code.
_______________________"You're using a screwdriver to nail some glue to a ming vase. " -ToohrVyk
Lol i sappose you misunderstood me. Put the [ source] [ /source] around your code that way it makes it into a scroll'able window and doesnt take up as much room =)

____________________________"This just in, 9 out of 10 americans agree that 1 out of 10 americans will disagree with the other 9"- Colin Mochrie
ahhh, i see. lol woops >.> Wow, that's a lot nicer, it even color codes it for you too. Is there a way to bypass the color coding for things like the .txt file, but still have it in a scroll box?
Quote:Original post by KuroKitten
ahhh, i see. lol woops >.> Wow, that's a lot nicer, it even color codes it for you too. Is there a way to bypass the color coding for things like the .txt file, but still have it in a scroll box?


It doesn't look like you can do that directly, but you could set the language it does syntax highlighting for to something like assembly, where most if not all of the keywords are not used in common english. Check the FAQ to see how to do that.
______________________________________________________________________________________The Phoenix shall arise from the ashes... ThunderHawk -- ¦þ"So. Any n00bs need some pointers? I have a std::vector<n00b*> right here..." - ZahlmanMySite | Forum FAQ | File Formats______________________________________________________________________________________
You may want to replace your StrToInt () function with standard C library functions: sprintf () or atoi (). These are dedicated functions and works more efficiently (in term of both flexibility and performance) than yours in most circumstances.
[Edit]: I saw nprz's post below, you're right. I forgot about C++ cin and cout.

As an alternative: I'll create a message-only window and use WM_TIME message instead. When the timer needs a reset, the next timeout will be (NextTime - CurrentTime), by that your application will use (almost) zero system resource most of the time.

Btw, your program is nice, may you post a link to the exe after (if you'd like to) changing with these minor suggestions ?.

[Edited by - Skeleton_V@T on December 19, 2005 10:45:47 PM]
--> The great thing about Object Oriented code is that it can make small, simple problems look like large, complex ones <--

This topic is closed to new replies.

Advertisement