The slurp gets problematic for very large files, of course, so here is a version that uses a fixed buffer. It runs at essentially the same speed - but uses a constant amount of memory instead.
#!/opt/bin/perl use strict; use warnings; use Time::HiRes qw (gettimeofday tv_interval); my $file = shift; my $start_time = [gettimeofday]; open(FH,$file) or die("Can't open file: $!\n"); binmode FH; my $bytes = -s $file; my $cursor = 0; my $stride = 4000000; my $counted_bits = 0; while (1) { my $buffer; my $result = read(FH, $buffer, $stride); if (0 == $result) { last; } elsif (not defined $result) { warn("Error reading from $file: $!\n"); last; } my $bits = unpack "B*", $buffer; $counted_bits += $bits =~ tr/1/1/; } close (FH); print "Bits: $counted_bits\n"; my $elapsed = tv_interval($start_time); my $rate = $bytes / $elapsed; print "Bytes per second: $rate\n";

In reply to Re^2: counting set bits in binary file by snowhare
in thread counting set bits in binary file by dwhite20899

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.