開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs(Text Editor)
- プログラミング言語: Perl
『続・初めてのPerl 改訂版』(Randal L. Schwartz, brian d foy, Tom Phoenix 著、伊藤 直也、田中 慎司、吉川 英興 監訳、株式会社ロングテール/長尾 高弘 訳、オライリー・ジャパン、2006年、ISBN4-87311-305-9)の9章(リファレンスを使った実践的なテクニック)の9.9(練習問題)2を解いてみる。
その他参考書籍
2.
コード(BBEdit)
sample.pl
#!/usr/bin/env perl
use strict;
use warnings;
use 5.016;
use utf8;
binmode STDOUT, ':utf8';
binmode STDIN, ':utf8';
binmode STDERR, ':utf8';
use Benchmark q(timethese);
my @files = glob "/opt/local/bin/*";
my $sort = q{ my @sorted = sort { -s $a <=> -s $b } @files;};
my $schwartz = q{
my @sorted = map {
$_->[0];
} sort {
$a->[1] <=> $b->[1];
} map {
[$_, -s $_];
} @files;
};
my $count = 10 ** 6;
timethese($count, {
sort => $sort,
schwartz => $schwartz
});
入出力結果(Terminal)
$ ./sample.pl
Benchmark: timing 1000000 iterations of schwartz, sort...
schwartz: 1 wallclock secs ( 0.52 usr + 0.01 sys = 0.53 CPU) @ 1886792.45/s (n=1000000)
sort: 1 wallclock secs ( 0.44 usr + 0.01 sys = 0.45 CPU) @ 2222222.22/s (n=1000000)
$
ちなみにpython3.3の場合。
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
## Copyright (C) 2013 by kamimura
#-*- coding: utf-8 -*-
import os
import glob
import timeit
sort1 = """
import glob
import os
def f(x):
if os.path.isfile(x):
return os.path.getsize(x)
return 0
result = sorted(glob.glob('/opt/local/bin/*'), key=f)
"""
sort2 = """
import glob
import os
def f(x):
if os.path.isfile(x):
return os.path.getsize(x)
return 0
files = glob.glob('/opt/local/bin/*')
files.sort(key=lambda x: f(x))
result = files
"""
schwartz_sorted = """
import os
import glob
def f(x):
if os.path.isfile(x):
return os.path.getsize(x)
return 0
result = list(map(
lambda x:x[0],
sorted(
map(lambda x: [x, f(x)],
glob.glob('/opt/local/bin/*')),
key=lambda x: x[1]
)
))
"""
schwartz_sort = """
import os
import glob
def f(x):
if os.path.isfile(x):
return os.path.getsize(x)
return 0
files = glob.glob('/opt/local/bin/*')
files = list(map(lambda x: [x, f(x)], files))
files.sort(key=lambda x: x[1])
result = list(map(lambda x: x[0], files))
"""
print('sorted')
print(timeit.timeit(sort1, number=100))
print('schwartz/sorted')
print(timeit.timeit(schwartz_sorted, number=100))
print('sort')
print(timeit.timeit(sort2, number=100))
print('schwartz/sort')
print(timeit.timeit(schwartz_sort, number=100))
入出力結果(Terminal)
$ ./sample.py sorted 4.737505964993034 schwartz/sorted 4.740311153989751 sort 4.596231703006197 schwartz/sort 4.797815569036175 $
0 コメント:
コメントを投稿