OcK OcK - 3 months ago 42
C Question

simple program using too much cpu

Edit : Why is this question getting downvoted?

I am wondering why the following code uses very much CPU. I can not see anything, which could cause this issue.
It is the following code.

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

void main(){

clock_t begin;
double time_spent;
int i = 0;


begin = clock();
time_spent = 0;
while(time_spent < 60) {
time_spent = (double)(clock() - begin) / CLOCKS_PER_SEC;
printf("Eine Minute vergangen %i\n", i);

This program basically checks when one minute has elapsed, counts how many minutes are done yet and prints it out.

I am running this on ubuntu terminal and it sucks my CPU. Can someone help me figuring this out?

alk alk

Sitting at the bus station, waiting for the bus to arrive in an hour or so, you do not look at your watch every second, milli second, ..., don't you? But that's exactly what you told the CPU to do, even worth you told it to "look up the time" as often as possible, as fast as it can.

So depending on the accuracy necessary tell the CPU to take a longer or shorter break between checking the time.

If an accuracy of 1s would be enough, then wait 1s between testing the time by adding


into the inner while-loop.