如何使自己的定时器没有标准库? [英] How can I make my own timer without standard library?

查看:174
本文介绍了如何使自己的定时器没有标准库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一些特定数量的迭代,我可以使用 for循环,以便它完全需要1秒的循环完全执行?例如下面的代码在我的机器上执行0.125s:

  #include< iostream> 
#include< cmath>

using namespace std;

int main(){
long long a = 0;

for(a = 0; a< = pow(10,4); a ++);然而,一个< = 8 * pow(10,4)花费了0.206美元s。编译器是GCC 4.9.2。 IDE是代码块。



我的电脑的规格:操作系统:Windows 8.1

解决方案

我根据收到的意见发布此问题的答案



不能制作计时器,因为:




  • 时间迭代将采取是不可预测的,这不仅取决于使用的CPU,但是你需要考虑电源管理,调度程序。 (通过tux3)

  • 必须使用实时操作系统来完成。非实时操作系统中有太多的抖动。 Windows可以决定调度其他进程一段时间,或使用CPU为例如。内核网络,磁盘I / O等,以抢占时序。 (By nos)


  • 在托管环境中不能使用标准C ++来自己定时。计时器实质上是与OS调度程序通信的机制,并且一个需要针对其的平台特定OS服务。 (By Kerrek SB)


  • 编译器会优化这样一个循环,并通过死代码消除(由πάνταῥεῖ和Jongware) >



Is there some specific number of iterations, that I could make using a for loop, so that it exactly takes 1 second for the loop to be executed completely? For example the following code took 0.125s on my machine to execute:

#include <iostream>
#include <cmath>

using namespace  std;

int main(){
    long long a=0;

    for (a=0;a<=pow(10,4);a++);
}

Though, a <= 8*pow(10,4) took 0.206 s. Compiler is GCC 4.9.2. IDE is codeblocks.

My PC's Specs: OS: Windows 8.1

解决方案

I am posting this answer to your question, as per the comments received.

It is not possible to make a timer because:

  • The time that an iteration will take is unpredictable, this depends not only on the CPU used, but you need to take into account power management, the scheduler. (By tux3)
  • one would have to use a real time OS to accomplish that. There's too much jitter in non realtime OSs. Windows could decide to schedule other processes for a while, or use the CPU for e.g. kernel networking, disk I/O etc. that preempts the timing. (By nos)

  • One can't "make own timer" in a hosted environment just in standard C++. A timer is essentially a mechanism to communicate with the OS scheduler, and one needs platform-specific OS services for that. (By Kerrek SB)

  • The compiler would optimize such a loop and will remove it through dead-code elimination (By πάντα ῥεῖ and Jongware).

这篇关于如何使自己的定时器没有标准库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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