简体   繁体   English

如何使用time.h库创建计时器?

[英]How do I create a timer using the time.h library?

This is not a homework, it's more of a challenge from our prof but I'll be tagging it as one nonetheless. 这不是家庭作业,这更多的是我们教授的挑战,但是我还是将其标记为一个。

The problem is to create a typing game that has 3 levels with matching difficulty, different time limits (in seconds) and scores. 问题是要创建一个具有3个级别的打字游戏,它们具有匹配难度,不同的时间限制(以秒为单位)和得分。 Now I don't have any problems with the program itself, what I'm having problem is implementing the timer, that should be OS independent (I assume, since the only hint says it's time.h ). 现在我对程序本身没有任何问题,我遇到的问题是实现计时器,该计时器应该独立于操作系统(我想,因为唯一的提示是time.h)。 What I did is wrong, for it's only a rough guess from what I read about the time.h, it's also ugly code: 我所做的是错误的,因为根据我所读的时间只是一个粗略的猜测。h,它也是丑陋的代码:

time_t start;
int timer = time(&start);
...
time_t current;
for(ctr=0;ctr<10;ctr++)
{
    ...
    if(time(&current) == (timer+40))
      {    
           break;
      }
    ...
}

Works sometimes but doesn't most of the time since it's only a rough guess. 有时是可行的,但在大多数情况下都行不通,因为这只是一个粗略的猜测。 Any suggestions would be appreciated. 任何建议,将不胜感激。

First off, you don't need to provide a time_t* argument to the time function. 首先,您不需要time函数提供time_t*参数。 If you're just going to use its return value, it's fine (and very common) to call time(NULL) . 如果仅使用它的返回值,则调用time(NULL)很好(而且很常见time(NULL) That way you can eliminate the start and current variables if they aren't otherwise being used. 这样,如果不使用startcurrent变量,则可以消除它们。

Second, the return value from time is time_t , not int , so timer should be of type time_t . 其次, time的返回值为time_t ,而不是int ,因此timer的类型应为time_t

Finally, look at your test 最后看看你的测试

if(time(&current) == (timer+40))

and consider what happens if the time passed 40 seconds since the start while you were doing something else above the test, and is now, say, 43 second since the start. 并考虑一下,如果您从测试开始经过40秒,而您又在测试之前进行了其他操作,而现在距启动43秒,那会发生什么。 Don't you still want to break? 您还不想休息吗? So is == the appropriate test? 那么==是适当的测试吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM