Skip to content

Instantly share code, notes, and snippets.

@kwatch
Created September 14, 2014 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwatch/0132268e0c38741fe59a to your computer and use it in GitHub Desktop.
Save kwatch/0132268e0c38741fe59a to your computer and use it in GitHub Desktop.
str.endswith() と re.search() のベンチマーク
# -*- coding: utf-8 -*-
import sys, re
from benchmarker import Benchmarker
try:
xrange
except:
xrange = range
N = 100000
for bm in Benchmarker(width=30, cycle=10, extra=1):
string = "foo-bar-baz.jpg"
with bm.empty():
for _ in xrange(N):
pass
with bm("re.search()"):
for _ in xrange(N):
re.search(r'\.(png|gif|jpg)', string)
with bm("re.compile().search()"):
rexp = re.compile(r'\.(png|gif|jpg)')
for _ in xrange(N):
rexp.search(string)
with bm("str.endswith() #1"):
for _ in xrange(N):
string.endswith((".png", ".gif", ".jpg"))
with bm("str.endswith() #2"):
suffixes = (".png", ".gif", ".jpg")
for _ in xrange(N):
string.endswith(suffixes)
### Result example on CPython 3.4.1:
r"""
## Ranking real
str.endswith() #1 0.0412 (100.0%) *************************
str.endswith() #2 0.0450 ( 91.5%) ***********************
re.compile().search() 0.0818 ( 50.3%) *************
re.search() 0.2867 ( 14.4%) ****
## Ratio Matrix real [01] [02] [03] [04]
[01] str.endswith() #1 0.0412 100.0% 109.3% 198.7% 696.2%
[02] str.endswith() #2 0.0450 91.5% 100.0% 181.8% 636.8%
[03] re.compile().search() 0.0818 50.3% 55.0% 100.0% 350.3%
[04] re.search() 0.2867 14.4% 15.7% 28.5% 100.0%
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment