简单的 <Time.h>程序占用大量 CPU [英] Simple <Time.h> program takes large amount CPU

查看:38
本文介绍了简单的 <Time.h>程序占用大量 CPU的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过在 VS 中编写一些简单的东西来熟悉 C time.h 库.下面的代码只是每两秒打印一次加到自身的 x 的值:

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;
}

我担心的是该程序占用的 CPU 数量,大约为 22%.我认为这个问题源于 clockTemp 的不断更新(就在 while 语句下方),但我不确定如何解决这个问题.有没有可能是visual studio的问题,还是有什么特殊的时间检查方法?

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?

代码需要睡眠功能,这样它就不需要一直运行.我用 #include 添加了 sleep 并将 Sleep (2000)//2 second sleep 放在 while 的末尾

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) {...睡眠(2000);}

推荐答案

问题不在于您查看当前时间的方式.问题是没有什么可以限制循环运行的频率.您的程序会继续尽可能快地执行语句,并占用大量处理器时间.(在没有其他程序的情况下,在单线程 CPU 上,它将使用 100% 的处理器时间.)

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.)

您需要在循环中添加一个sleep"方法,这将向处理器表明它可以在短时间内停止处理您的程序.有很多方法可以做到这一点;这个问题有一些例子.

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.

这篇关于简单的 &lt;Time.h&gt;程序占用大量 CPU的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆