Advertisement
DRVTiny

Threads vs Async

Mar 10th, 2017
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.01 KB | None | 0 0
  1. #!/usr/bin/perl
  2. use 5.16.1;
  3. use Thread::Pool::Simple;
  4. use threads::shared;
  5. use Redis;
  6. use Time::HiRes qw(time);
  7.  
  8. use constant {
  9.   OBJS_N=>2000,
  10.   SLICE_N=>10,
  11. };
  12.  
  13. my %resT :shared;
  14. my %resS;
  15.  
  16. my $r=Redis->new;
  17. $r->flushdb;
  18. $r->set("s$_",int(rand(2000))) for 0..1999;
  19. $r->quit;
  20. undef $r;
  21.  
  22.  
  23. my $pool=Thread::Pool::Simple->new(
  24.   'min'=>4,  
  25.   'max'=>128,
  26.   'do'=>[sub {  
  27.     return unless my @jobs=@_;
  28.     my $r=Redis->new;
  29.     for my $oid ( map 's'.$_, @jobs ) {
  30.       $r->get($oid, sub { $resT{$oid}=shift })
  31.     }
  32.     $r->wait_all_responses
  33.    }],
  34. );
  35.  
  36. my @id;
  37. my $slice=OBJS_N/SLICE_N;
  38.  
  39. my $startTick=time();
  40. $id[$_]=$pool->add(($slice*$_)..($slice*($_+1)-1)) for 0..(SLICE_N-1);
  41. $pool->join;
  42. my $elapT=time()-$startTick;
  43.  
  44. say 'Estimated with threads: ', $elapT;
  45.  
  46. $startTick=time();
  47. $r=Redis->new;
  48. for my $oid (map 's'.$_, 0..1999) {
  49.   $r->get($oid, sub { $resS{$oid}=shift })
  50. }
  51. $r->wait_all_responses;
  52. my $elapS=time()-$startTick;
  53.  
  54. say 'Estimated with async-only: '.$elapS;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement