How do I implement instantaneous, yet buffered output in OCaml?

回眸只為那壹抹淺笑 提交于 2021-01-29 05:01:09

问题


I am writing a Prolog interpreter in OCaml and I want it to offer the following feature:

  • Character-based output is buffered.

  • Output appears instantaneously, say, within 0.05 seconds.

  • There is no need to use explicit flush_output/0 operations.

  • Buffer flushing operations are done automatically, but not at every put_char.

Here's what I came up with:

  • Upon program startup I ...

    • ... install a signal handler for SIGALRM and ...
    • ... use Unix.setitimer for starting a periodic timer.
  • The timer is a real-time timer (ITIMER_REAL).

  • The timer fires every 0.05 seconds.

  • All the signal handler does is: flush_all ().

What downsides does this have?

And if so, which implementation alternatives do I have?


回答1:


Basically your code is doing a lot of work constantly in order to flush characters once in a while. So this is an inefficient use of CPU time. You might try running top (if on a Unix system) to see how much CPU this approach is consuming.

In the big picture CPU time is amazingly cheap these days. But I wouldn't write code like this--it feels too wasteful. Maybe I'm too old school about this, however.

It would possibly be less wasteful of resources just to turn off buffering of your output files. I'm not sure why you're so insistent on having buffering, since you're not really using it for much.

Another downside of this approach is that you have usurped the timer and alarm mechanism for use by the implementation. So it's not available (or not as readily available) for user code.

If you could be a little more specific about what you mean by "character-based output" it might be possible to think of another mechanism. But I can't think of anything myself right off.



来源:https://stackoverflow.com/questions/62852066/how-do-i-implement-instantaneous-yet-buffered-output-in-ocaml

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