Created
July 31, 2012 11:11
-
-
Save fukata/3216273 to your computer and use it in GitHub Desktop.
redis sdiff example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use utf8; | |
use Redis; | |
srand(time ^ ($$ + ($$ << 15))); | |
my $max_rand = 100000000000; | |
my $keybase = 'HOGE::'; | |
my $master_set_key = 'HOGE::MASTER'; | |
my $redis = Redis->new; | |
my $result = $redis->select(1); | |
sub rand_items { | |
my ($max_item) = @_; | |
my @items = (); | |
my %item_map = (); | |
my $count = 0; | |
while ( $count < $max_item ) { | |
my $r = "ITEM_" . int(rand($max_rand)); | |
next if $item_map{$r}; | |
$item_map{$r} = 1; | |
push @items, $r; | |
$count++; | |
} | |
return @items; | |
} | |
sub rand_selected_items { | |
my ($items, $max_selected_items) = @_; | |
my @selected_items = (); | |
my %selected_map = (); | |
my $count = 0; | |
while ( $count < $max_selected_items ) { | |
my $k = int(rand(@$items)); | |
next if $selected_map{$k}; | |
$selected_map{$k} = 1; | |
push @selected_items, "${keybase}ITEM::" . $items->[$k]; | |
$count++; | |
} | |
return @selected_items; | |
} | |
sub create_set { | |
my ($items) = @_; | |
foreach my $item ( @$items ) { | |
$redis->sadd($master_set_key, $item); | |
$redis->sadd("${keybase}ITEM::$item", $item); | |
} | |
} | |
my ( $max_item, $max_selected_items ) = @ARGV; | |
### $max_item | |
### $max_selected_items | |
my @items = rand_items($max_item); | |
### @items | |
my @selected_items = rand_selected_items(\@items, $max_selected_items); | |
### @selected_items | |
$redis->flushdb; | |
create_set(\@items); | |
my @diff_items = $redis->sdiff($master_set_key, @selected_items); | |
### @diff_items | |
# | |
# perl -MSmart::Comments ./redis-sdiff.pl 10000 9990 | |
# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment