回答編集履歴

1

続きが字数制限に引っかかったので少し追加

2023/03/31 13:22

投稿

退会済みユーザー
test CHANGED
@@ -44,5 +44,45 @@
44
44
  - mingw環境での新しめのgccで計測
45
45
  - boostの計測
46
46
  - 良さげなベンチマーク結果の調査
47
+
48
+ ### コード
49
+ ```python
50
+ class SubRepl:
51
+ def __init__(self, callback):
52
+ self.found = False
53
+ self.callback = callback
54
+ def get_callback(self):
55
+ def real_callback(m):
56
+ self.found = True
57
+ return self.callback(m)
58
+ return real_callback
59
+
60
+ import re
61
+ repl = SubRepl(lambda m: '_')
62
+ regex = re.compile('[\n  ]')
63
+ callback = repl.get_callback()
64
+
65
+ def hoge_normal(str):
66
+ return str.replace('\n','_').replace(' ', '_').replace(' ', '_')
67
+ def hoge_regexp(str):
68
+ return regex.sub('_', str)
69
+ def hoge_regexp2(str):
70
+ return regex.sub(callback, str)
71
+
72
+ import timeit
73
+ print(timeit.timeit(lambda: hoge_normal('hoge fuga piyo\n')))
74
+ print(timeit.timeit(lambda: hoge_regexp('hoge fuga piyo\n')))
75
+ print(timeit.timeit(lambda: hoge_regexp2('hoge fuga piyo\n')))
76
+ print(timeit.timeit(lambda: hoge_normal('hoge fuga piyo\nhoge fuga piyo\nhoge fuga piyo\nhoge fuga piyo\nhoge fuga piyo\n')))
77
+ print(timeit.timeit(lambda: hoge_regexp('hoge fuga piyo\nhoge fuga piyo\nhoge fuga piyo\nhoge fuga piyo\nhoge fuga piyo\n')))
78
+ print(timeit.timeit(lambda: hoge_regexp2('hoge fuga piyo\nhoge fuga piyo\nhoge fuga piyo\nhoge fuga piyo\nhoge fuga piyo\n')))
79
+ # 出力例
80
+ # 0.5004470729909372
81
+ # 0.9112305690068752
82
+ # 1.458983212010935
83
+ # 0.7863287159998436
84
+ # 3.1747756089898758
85
+ # 5.850148669996997
86
+ ```
47
87
  (続く)
48
88