Term::ReadKey works great, but if you're in a tight loop, there's no need to check it every time; it will slow you down big time. Take a look at this:
use Benchmark;
use Term::ReadKey;
ReadMode cbreak; # make sure we can ctrl-c it
timethese(10, {
'read_every' =>
sub { my $cnt = 0; while ($cnt < 1e5) { print "$cnt\n" if Read
+Key(-1); $cnt++ } },
'read_1000' =>
sub { my $cnt = 0; while ($cnt < 1e5) { print "$cnt\n" if not
+$cnt % 1000 and ReadKey(-1); $cnt++ } }
});
ReadMode restore; # Reset tty mode before exiting
[brad:foo]$ perl read_test.pl
Benchmark: timing 10 iterations of read_1000, read_every...
read_1000: 2 wallclock secs ( 1.18 usr + 0.04 sys = 1.22 CPU) @ 8
+.20/s (n=10)
read_every: 42 wallclock secs (29.19 usr + 10.88 sys = 40.07 CPU) @ 0
+.25/s (n=10)
Reading only every 1000 iterations, at least in this test, still catches every keystroke immediately.
Brad
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.