尽可能准确地安排活动的开始时间 [英] schedule the starting time of events as accurately as possible

查看:78
本文介绍了尽可能准确地安排活动的开始时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想安排一系列事件,以便大约最接近的 5ms,事件 N 的开始时间是 t0 + dt*N,其中 t0 是进程开始后的任意时间.如果事件被输出到终端,它们会定期发生而不会暂停或加速.如果它们是噪音,就会产生规律的节奏.这是我的第一次尝试.

I would like to schedule a series of events such that to about the nearest 5ms, the starting time of event N is t0 + dt*N, where t0 is some arbitrary time after the process starts. If the events were output to a terminal, they would occur regularly without pauses or speedups. If they were noises, it would produce a regular rhythm. This is my first attempt.

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

void fsleep(double t)
{
    time_t sec = floor(t);
    long nsec = 1e9*(t - sec);
    struct timespec s;
    s.tv_sec = sec;
    s.tv_nsec = nsec;
    nanosleep(&s, NULL);
}

int main(int argc, const char **argv)
{
    for (unsigned i = 0;; i++) {
        printf("%d\n", i);
        fflush(stdout);
        fsleep(0.334);
    }
}

即使在实时优先级(nice -n -20),这也是垃圾.整个时间都有明显的抖动,停顿长达 1 秒,然后连续打印出一大堆数字.为了测试它是否是我的终端,我制作了以下脚本:

It is total garbage, even at realtime priority (nice -n -20). There are noticeable jitters the entire time, with pauses of up to 1 second, after which a whole bunch of numbers are printed in a row. To test whether it was my terminal, I made the following script:

from time import sleep
from sys import stdin
def raw_stdin():
    """Switches stdin to a non-buffering, non-echoing mode,
    handing keystrokes directly to the program as soon as they're 
    received and printing nothing to the terminal."""
    import termios as t
    f = t.tcgetattr(stdin)
    f[3] &= ~(t.ICANON|t.ECHO)
    t.tcsetattr(stdin, t.TCSANOW, f)

raw_stdin()

for i in range(10000000):
    #sleep(.334)
    stdin.read(1)
    print(i)

如果我有规律地敲击任何键,即以相同的时间间隔在最接近的 10 毫秒左右,我会得到有规律的输出,零犹豫.这证明终端的响应能力足够强,而且我正在尝试做的事情是可能的.我很难想象电脑不能做我用左手食指可以做的事情.

If I hit any key regularly, i.e. with the same time intervals between strokes down to the nearest 10ms or so, I get regular outputs, with zero hesitations. This proves the terminal is more than responsive enough, and that what I'm trying to do is possible. I have a hard time imagining the computer can't do something I can do with my left index finger.

我认为这可能与我的 linux 内核有关.我很想知道如果在 Windows 或其他 linux 内核上运行会发生什么.

I think it might have something to do with my linux kernel. I'd be interested to know what happens if this is run in windows, or on other linux kernels.

推荐答案

我想通了.它一直是我的终端(xfce4-terminal).其中有一个错误会扰乱实时输出.如需了解详情,请参阅 https://stackoverflow.com/a/47744798/1840698.

I figured it out. It was my terminal all along (xfce4-terminal). There's a bug in it that messes up realtime output. See https://stackoverflow.com/a/47744798/1840698 for more.

这篇关于尽可能准确地安排活动的开始时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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