in reply to Re^2: Wanting some clarification / opinions on MCE vs Threads
in thread Wanting some clarification / opinions on MCE vs Threads
(I should say my threads equivalent)
Hm. No offence but, Ew! :)
Remember that MCE is a wrapper (actually a suite of wrappers, or is that sweet wrapper:) over the top of threads(and other things), providing syntactic sugar for simple operations.
You can easily do the same yourself. Say write TGrep.pm:
package TGrep; use strict; use threads; use Thread::Queue; our $WORKERS = 4; sub g_proxy { my( $code, $Qin, $Qout ) = @_; $Qout->enqueue( $code->() ? $_ : () ) while local $_ = $Qin->dequ +eue; $Qout->enqueue( undef ); } sub tgrep(&@) { my $workers = $WORKERS; my $code = shift; my( $Qin, $Qout ) = map Thread::Queue->new, 1..2; async( \&g_proxy, $code, $Qin, $Qout )->detach for 1 .. $workers; $Qin->enqueue( map{ ref $_[0] ? @{ $_ } : $_ } @_ ); $Qin->enqueue( (undef) x $workers ); my @results; push @results, $_ while $_ = $Qout->dequeue; return wantarray ? @results : \@results; } sub import { no strict 'refs'; my $pkg = caller; *{ $pkg . '::' . $_ } = *{ $_ } for qw[ tgrep ]; } 1;
Then write:
#! perl -slw use strict; use TGrep; use Time::HiRes qw[ time ]; our $N //= 1e3; my $start = time; my @a = tgrep{ $_ % 5 == 0 } [ 1..$N ]; printf "Took %.9f seconds\n", time() -$start; print scalar @a; __END__ C:\test>t-tgrep -N=1e5 Took 3.830074787 seconds 20000
Of course, you'd probably be better sticking to grep for such simple things:
$t=time; my @a = grep{ $_%5 == 0 } 1 .. 1e6; print time-$t;; 0.18144702911377
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Wanting some clarification / opinions on MCE vs Threads
by jmmitc06 (Beadle) on Feb 05, 2015 at 14:50 UTC | |
by BrowserUk (Patriarch) on Feb 05, 2015 at 16:47 UTC | |
by ikegami (Patriarch) on Feb 05, 2015 at 19:26 UTC | |
by Anonymous Monk on Feb 05, 2015 at 22:13 UTC | |
by ikegami (Patriarch) on Feb 05, 2015 at 15:56 UTC | |
|
Re^4: Wanting some clarification / opinions on MCE vs Threads
by karlgoethebier (Abbot) on Feb 07, 2015 at 13:40 UTC | |
by BrowserUk (Patriarch) on Feb 07, 2015 at 13:44 UTC |