Simple <Time.h> program takes large amount CPU

最后都变了- 提交于 2021-02-17 07:08:48

问题


I was trying to familiarize myself with the C time.h library by writing something simple in VS. The following code simply prints the value of x added to itself every two seconds:

int main() {
    time_t start = time(NULL);
    time_t clock = time(NULL);
    time_t clockTemp = time(NULL); //temporary clock

    int x = 1;

    //program will continue for a minute (60 sec)
    while (clock <= start + 58) {
        clockTemp = time(NULL);
        if (clockTemp >= clock + 2) { //if 2 seconds has passed
            clock = clockTemp;
            x = ADD(x);
            printf("%d at %d\n", x, timeDiff(start, clock));
        }
    }
}

int timeDiff(int start, int at) {
    return at - start;
}

My concern is with the amount of CPU that this program takes, about 22%. I figure this problem stems from the constant updating of the clockTemp (just below the while statement), but I'm not sure how to fix this issue. Is it possible that this is a visual studio problem, or is there a special way to check for time?

Solution

the code needed the sleep function so that it wouldn't need to run constantly. I added sleep with #include <windows.h> and put Sleep (2000) //2 second sleep at the end of the while

while (clock <= start + 58) { ... Sleep(2000); }


回答1:


The problem is not in the way you are checking the current time. The problem is that there is nothing to limit the frequency with which the loop runs. Your program continues to execute statements as quickly as it can, and eats up a ton of processor time. (In the absence of other programs, on a single-threaded CPU, it would use 100% of your processor time.)

You need to add a "sleep" method inside your loop, which will indicate to the processor that it can stop processing your program for a short period of time. There are many ways to do this; this question has some examples.



来源:https://stackoverflow.com/questions/35259977/simple-time-h-program-takes-large-amount-cpu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!