问题
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.
- ... install a signal handler for
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