如何在OCaml中实现瞬时但已缓冲的输出? [英] How do I implement instantaneous, yet buffered output in OCaml?

查看:44
本文介绍了如何在OCaml中实现瞬时但已缓冲的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在OCaml中编写Prolog解释器,并希望它提供以下功能:

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

  • 基于字符的输出是 buffered .

输出瞬时出现,例如,在0.05秒之内.

Output appears instantaneously, say, within 0.05 seconds.

不需要使用显式的 flush_output/0 操作.

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

缓冲区刷新操作会自动完成,但不会在每个 put_char 处执行.

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

这是我想出的:

  • 我在程序启动时...

  • Upon program startup I ...

  • ...为 SIGALRM 和...
  • 安装信号处理程序
  • ...使用 Unix.setitimer 启动定期计时器.
  • ... install a signal handler for SIGALRM and ...
  • ... use Unix.setitimer for starting a periodic timer.

该计时器是一个实时计时器( ITIMER_REAL ).

The timer is a real-time timer (ITIMER_REAL).

计时器每0.05秒触发一次.

The timer fires every 0.05 seconds.

所有信号处理程序所做的就是: flush_all().

All the signal handler does is: flush_all ().

这有什么缺点?

如果是的话,我有哪些替代方案?

And if so, which implementation alternatives do I have?

推荐答案

基本上,您的代码会不断地做很多工作,以便不时刷新字符.因此,这是对CPU时间的低效使用.您可以尝试运行 top (如果在Unix系统上),以查看此方法消耗了多少CPU.

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.

从总体上看,这些天CPU时间非常便宜.但是我不会写这样的代码-感觉太浪费了.但是,也许我对此太过老了.

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.

这篇关于如何在OCaml中实现瞬时但已缓冲的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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