On 9/24/07, Ilmari Heikkinen <ilmari.heikkinen / gmail.com> wrote:
> On 9/22/07, Nobuyoshi Nakada <nobu / ruby-lang.org> wrote:
> > Hi,
> >
> > At Fri, 21 Sep 2007 07:05:10 +0900,
> > Ruby Maniac wrote in [ruby-talk:270110]:
> > > def scramble(fname)
> > >     _fname = fname + ".scrambled"
> >     File.new(fname, "rb") do |f|
> >       File.new(_fname, "wb+") do |ff|
> >         ff.write(f.read.tr("\0-\177", "\200-\377"))
> >       end
> >     end
> > > end
> >
> > --
> > Nobu Nakada
> >
>
> And the benchmark results for the above code on a 6.7M file:
>
> $ time ruby -rscramble -e 'scramble_original("trace")'
>
> real    0m11.626s
> user    0m9.781s
> sys     0m1.844s
>
> $ time ruby -rscramble -e 'scramble_nobu("trace")'
>
> real    0m0.099s
> user    0m0.044s
> sys     0m0.032s

And here's a C version:

$ time ./scramble trace trace.scrambled

real	0m0.063s
user	0m0.044s
sys	0m0.020s

$ cat scramble.c # I'm no C wiz so pardon the sucky error handling.
#include <stdlib.h>
#include <stdio.h>

#define BUF_SIZE 4096

int main(int argc, char** argv) {
  FILE *in_f, *out_f;
  char *buf;
  int i, rsz, wsz;

  if (argc != 3) {
    printf("USAGE: %s INFILE OUTFILE\n", argv[0]);
    return 1;
  }

  buf = (char *)malloc(BUF_SIZE);
  if (NULL == buf) {
    printf("Failed to allocate buffer\n");
    return 8;
  }

  in_f = fopen(argv[1], "r");
  if (NULL == in_f) {
    printf("Failed to open input file %s\n", argv[0]);
    return 2;
  }

  out_f = fopen(argv[2], "w");
  if (NULL == out_f) {
    printf("Failed to open output file %s\n", argv[1]);
    fclose(in_f);
    return 4;
  }

  while (0 != (rsz = fread(buf, 1, BUF_SIZE, in_f))) {
    for(i=0; i<rsz; i++)
      buf[i] |= 0x80;
    wsz = fwrite(buf, 1, rsz, out_f);
    if (wsz != rsz) {
      printf("Failed to write to output file\n");
      break;
    }
  }

  fclose(in_f);
  fclose(out_f);

}