schedule the starting time of events as accurately as possible

倖福魔咒の 提交于 2020-01-07 04:28:09

问题


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

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)

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.

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.


回答1:


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.



来源:https://stackoverflow.com/questions/47735431/schedule-the-starting-time-of-events-as-accurately-as-possible

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