in reply to RC4 cipher performance

Not minding that Perl just isn't suited to bit-fiddling tasks like this, I wanted to see the CPU-meter of my new machine go to 100%. I implemented a threaded version of your program, which runs about 3 to 4 times as fast on my 4-CPU machine by processing sets of 10000 keys in every thread.

The conversion to threaded code was fairly easy by using a queue through which all batches of keys to be tested go through. The main thread produces batches of 10000 keys and stuffs them into the queue, and goes to sleep once it finds that the queue contains more than 4 batches. Each worker thread retrieves a batch and crunches on it.

In a real program, there would be a second queue for communicating the status/success of every thread back to the main thread.

#!/perl/bin/perl use strict; use Crypt::RC4; use Time::HiRes; use threads; use Thread::Queue; my $max_threads = 4; my $data1="C5C444220AD6FB08972792318300CC703814513EE013AF97B94FF9ACF23 +F9C8F0E748C04B2E18BB5A1B491BB73E23EC9A4233B9BCDE4854FD03DCBAC4B3E9EA0 +0F5BF7A3A119B0FF2E66C9DD96E7F4F0972959082601AA5DD202DFB0 5039CA4FDC280517E244353690C0DE1A"; my $foo1=pack('H*',$data1); my $dt=time; print "$dt Start \n"; my $batchsize = 10000; my $key="A"; # The message queue through w my $jobs = Thread::Queue->new(); # Create the worker threads for (1..$max_threads) { async { my $ct; while ( 1 ){ my $start = time; my $items = $jobs->dequeue; my $SKIP=0; for my $key (@$items) { my $ucrypt=RC4($key,$foo1); my $clen = length($ucrypt); my @uchar = split(//,$ucrypt); for my $i (0..$#uchar) { my $val = ord($uchar[$i]); if($val>127) { $SKIP=1; last; } } if ($SKIP == 0 ){ print "matched using key:$key \n"; print "$ucrypt \n"; } }; my $end = time; print $end - $start," seconds\n"; printf "%0.2f items per second\n", @$items / ($end - $star +t); } }; } while (1) { my @batch = map { $key++ } 1 .. $batchsize; $jobs->enqueue(\@batch); my $sleep = 1; while ($jobs->pending() > $max_threads) { sleep $sleep; $sleep *= 2; }; }

Replies are listed 'Best First'.
Re^2: RC4 cipher performance
by jaiello (Novice) on Nov 15, 2008 at 23:17 UTC
    This is nice. I made some small modifications. I always wanted to use threads in perl. I have a great application and might reuse this code :)

    One mod was to print the key when the batch was finished. Since L already know the key I an tell if the code works or not. In this case, the key is never incremented and is always A. The map function does not seem to work.

    It was nice to see that each thread processes about 1666 iterations per second. It was not a good idea to shell for date. I actually know better than that. Thanks