I got this info off a website. tells u how to make a clock in C++... can anyone tell me how to make it so the PC doesn't use 100% cpu? if u look in task manager ull see <ProjectName> is using 100% cpu

// crt_clock.c
// This example prompts for how long
// the program is to run and then continuously
// displays the elapsed time for that period.
//

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void sleep( clock_t wait );

int main( void )
{
   long    i = 6000000L;
   clock_t start, finish;
   double  duration;

   // Delay for a specified time.
   printf( "Delay for three seconds\n" );
   sleep( (clock_t)3 * CLOCKS_PER_SEC );
   printf( "Done!\n" );

/*
   // Measure the duration of an event.
   printf( "Time to do %ld empty loops is ", i );
   start = clock();
   while( i-- ) 
      ;
   finish = clock();
   duration = (double)(finish - start) / CLOCKS_PER_SEC;
   printf( "%2.1f seconds\n", duration );*/
   system("PAUSE");
}

// Pauses for a specified number of milliseconds.
void sleep( clock_t wait )
{
   clock_t goal;
   goal = wait + clock();
   while( goal > clock() )
      ;
}

Recommended Answers

All 4 Replies

>can anyone tell me how to make it so the PC doesn't use 100% cpu?
It uses 100% CPU because you're using a busy loop to pause. A true fix for the problem is "don't do that". Use some form of pause that puts the thread to sleep without affecting the other running threads. Unfortunately, there's no standard way to do that, so you'll need to look to your implementation and OS for libraries that support what you need.

For example, on Windows you might do this:

#include <stdio.h>
#include <windows.h>

int main ( void )
{
  printf ( "Delay for three seconds\n" );
  Sleep ( 3000 );
  printf ( "Done!\n" );
}

ah awesome it works thx!:)

#include<iostream>
#include<string>
#include<cstdlib>
#include<ctime>
#include<windows.h>

using namespace std;

int main()
{
time_t now = time(0);               
tm *ltm = localtime(&now);              //get local time
int sec=ltm->tm_sec,hr=ltm->tm_hour,min=ltm->tm_min;string ampm=" AM"; // set clock to current time
if(ltm->tm_hour >= 13 || ltm->tm_hour == 0)
{if(hr != 0) {hr = (ltm->tm_hour - 12);ampm=" PM";} else hr = 12;}
// clock loop
while(true){
Sleep(1000); system("cls"); //one second delay
cout <<hr<<":"<<min<<":"<<sec<<ampm<<endl;
sec++;
if(sec == 59){min++; sec=0;
           if(min==60){ hr++; sec=0;min=0;
           if(hr==13){hr=1; if(ampm==" AM") ampm=" PM"; else ampm=" AM";}}}}
return 0;    
}

simple but working.

simple but working.

Who cares after 3 years?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.