unique_id int64 29 188k | target stringclasses 252
values | code stringlengths 22 299k | __index_level_0__ int64 0 1.21k |
|---|---|---|---|
73,752 | None | def __init__(el):
self.start()
def start(self) -> None:
self.start_time = time.time()
def elapsed_time(self) -> float:
return time.time() - self.start_time
class BenchmarkInfo(NamedTuple):
name: str
module: str
perform: Callable[[BenchmarkContext], object]
# Argument... | 0 |
54,196 | Callable[[Callable[[], T]], Callable[[], T]] | def benchmark( *,
prepare: Callable[[str | None], None] | None = None,
compiled_only: bool = False,
min_iterations: int | None = None,
strip_outlier_runs: bool = True,
stable_hash_seed: bool = Fals):
"""Define a benchmark.
Args:
prepare: If given, called ... | 1 |
169,124 | Callable[[BenchmarkContext], T] | def benchmark_with_context( func: Callable[[BenchmarkContext], T):
name = func.__name__
if name.startswith('__mypyc_'):
name = name.replace('__mypyc_', '')
name = name.replace('_decorator_helper__', '')
benchmark = BenchmarkInfo(name, func.__module__, func, None, False, None, True, F... | 2 |
109,551 | float | def run_once(enchmark_name: st):
for benchmark in benchmarks:
if benchmark.name == benchmark_name:
context = BenchmarkContext()
benchmark.perform(context)
return context.elapsed_time()
assert False, "unknown benchmark: %r" % benchmark_name
| 3 |
78,906 | str | def func_name(unc: Callable[..., object):
name = func.__name__
if name.startswith('__mypyc_'):
name = name.replace('__mypyc_', '')
name = name.replace('_decorator_helper__', '')
return name
# --- runbench.py ---
from __future__ import annotations
from importlib import import_module
from ... | 4 |
169,746 | float | def run_in_subprocess(enchmark: BenchmarkInfo,
binary: str | None,
compiled: bool,
priority: bool = False,
env: dict[str, str] | None = Non):
module = benchmark.module
program = 'import %s; import benchmarking as bm; print(... | 5 |
145,939 | float | def parse_elapsed_time(utput: byte):
m = re.search(rb"\belapsed: ([-+0-9.e]+)\b", output)
assert m is not None, 'could not find elapsed time in output:\n%r' % output
return float(m.group(1))
| 6 |
154,252 | list[float] | def smoothen(: list[float):
# Keep the lowest half of values
return sorted(a)[: (len(a) + 1) // 2]
| 7 |
38,512 | None | def run_benchmark(enchmark: BenchmarkInfo,
binary: str | None,
raw_output: bool,
priority: bool,
interpreted: bool,
compiled: bool,
min_iter: int,
mypy_repo: str | Non):
assert compiled or ... | 8 |
96,336 | str | def compile_benchmark(odule: str, raw_output: bool, mypy_repo: str | Non):
fnam = module.replace('.', '/') + '.py'
if not raw_output:
print('compiling %s...' % module)
env = os.environ.copy()
legacy_script = None
if mypy_repo:
# Use mypyc from specific mypy repository.
env['... | 9 |
123,788 | None | def import_all():
files = glob.glob('microbenchmarks/*.py')
files += glob.glob('benchmarks/*.py')
for fnam in files:
filepath = Path(fnam).resolve()
if filepath.name == '__init__.py' or filepath.suffix != '.py':
continue
benchmarks_root_dir = Path(__file__).parent.resolv... | 10 |
185,961 | None | def delete_binaries():
files = glob.glob(f'microbenchmarks/*.{BINARY_EXTENSION}')
files += glob.glob(f'benchmarks/*.{BINARY_EXTENSION}')
for fnam in files:
os.remove(fnam)
class Args(NamedTuple):
benchmark: str
mypy_repo: str | None
is_list: bool
raw: bool
priority: bool
c... | 11 |
158,921 | Args | def parse_args():
parser = argparse.ArgumentParser(
description="Run a mypyc benchmark in compiled and/or interpreted modes.")
parser.add_argument('benchmark', nargs='?',
help="name of benchmark to run (use --list to show options)")
parser.add_argument('--mypy-repo', metavar... | 12 |
28,508 | None | def main():
# Delete compiled modules before importing, as they may be stale.
delete_binaries()
# Import before parsing args so that syntax errors get reported.
import_all()
args = parse_args()
if args.is_list:
for benchmark in sorted(benchmarks):
suffix = ''
i... | 13 |
83,192 | None | def binary_trees():
# If unadjusted, most time will be spent doing GC.
gc.set_threshold(10000)
min_depth = 4
max_depth = 18 # Original uses 21, but it takes too long
stretch_depth = max_depth + 1
print("stretch tree of depth {} check: {}".format(stretch_depth, Tree(stretch_depth).check()))
... | 14 |
111,482 | None | def chain_test(: i6):
"""
This is the standard DeltaBlue benchmark. A long chain of equality
constraints is constructed with a stay constraint on one end. An
edit constraint is then added to the opposite end and the time is
measured for adding and removing this constraint, and extracting
and ex... | 15 |
35,780 | None | def projection_test(: in):
"""
This test constructs a two sets of variables related to each
other by a simple linear transformation (scale and offset). The
time is measured to change a variable on either side of the
mapping and to change the scale and offset factors.
"""
global planner
... | 16 |
137,451 | None | def change(: Variable, new_value: floa):
global planner
edit = EditConstraint(v, PREFERRED)
edits = OrderedCollection()
edits.append(edit)
assert planner is not None
plan = planner.extract_plan_from_constraints(edits)
for i in range(10):
v.value = float(new_value)
plan.exe... | 17 |
145,716 | None | def run_delta_blue(: i6):
chain_test(n)
projection_test(n)
@benchmark() | 18 |
113,535 | None | def deltablue():
n = 100
for i in range(10):
run_delta_blue(n)
# --- bm_float.py ---
"""
Artificial, floating point-heavy benchmark originally used by Factor.
Adapted to mypyc by Jukka Lehtosalo
"""
from __future__ import annotations
from math import sin, cos, sqrt, isclose
from benchmarking import... | 19 |
163,328 | Point | def maximize(oints: list[Point):
next = points[0]
for p in points[1:]:
next = next.maximize(p)
return next
@benchmark() | 20 |
10,336 | None | def bm_float():
n = POINTS
points = []
for i in range(n):
points.append(Point(i))
for p in points:
p.normalize()
result = maximize(points)
assert isclose(result.x, 0.8944271890997864)
assert isclose(result.y, 1.0)
assert isclose(result.z, 0.4472135954456972)
# --- bm_h... | 21 |
99,329 | bool | def constraint_pass(os: Pos, last_move: Optional[i64] = Non):
changed = False
left = pos.tiles[:]
done = pos.done
# Remove impossible values from free cells
free_cells: List[i64] = (list(range(done.count)) if last_move is None
else pos.hex.get_by_id(last_move).links)
... | 22 |
120,922 | List[Tuple[i64, i64]] | def find_moves(os: Pos, strategy: i64, order: i6):
done = pos.done
cell_id = done.next_cell(pos, strategy)
if cell_id < 0:
return []
if order == ASCENDING:
return [(cell_id, v) for v in done[cell_id]]
else:
# Try higher values first and EMPTY last
moves = list(rever... | 23 |
146,584 | None | def play_move(os: Pos, move: Tuple[i64, i64):
(cell_id, i) = move
pos.done.set_done(cell_id, i)
| 24 |
164,683 | None | def print_pos(os: Pos, output: IO[str):
hex = pos.hex
done = pos.done
size = hex.size
for y in range(size):
print(u_lit(" ") * (size - y - 1), end=u_lit(""), file=output)
for x in range(size + y):
pos2 = (x, y)
id = hex.get_by_pos(pos2).id
if done.alr... | 25 |
146,404 | i64 | def solved(os: Pos, output: StringIO, verbose: bool = Fals):
hex = pos.hex
tiles = pos.tiles[:]
done = pos.done
exact = True
all_done = True
for i in range(hex.count):
if len(done[i]) == 0:
return IMPOSSIBLE
elif done.already_done(i):
num: i64 = done[i][0... | 26 |
25,240 | i64 | def solve_step(rev: Pos, strategy: i64, order: i64, output: StringIO, first: bool = Fals):
if first:
pos = prev.clone()
while constraint_pass(pos):
pass
else:
pos = prev
moves = find_moves(pos, strategy, order)
if len(moves) == 0:
return solved(pos, output)
... | 27 |
157,744 | None | def check_valid(os: Po):
hex = pos.hex
tiles = pos.tiles
# fill missing entries in tiles
tot: i64 = 0
for i in range(i64(8)):
if tiles[i] > 0:
tot += tiles[i]
else:
tiles[i] = 0
# check total
if tot != hex.count:
raise Exception(
"... | 28 |
122,434 | object | def solve(os: Pos, strategy: i64, order: i64, output: StringI):
check_valid(pos)
return solve_step(pos, strategy, order, output, first=True)
# TODO Write an 'iterator' to go over all x,y positions
| 29 |
111,495 | Pos | def read_file(ile: st):
lines = [line.strip("\r\n") for line in file.splitlines()]
size = int(lines[0])
hex = Hex(size)
linei = 1
tiles = 8 * [0]
done = Done(hex.count)
for y in range(size):
line = lines[linei][size - y - 1:]
p = 0
for x in range(size + y):
... | 30 |
63,007 | None | def solve_file(ile: str, strategy: i64, order: i64, output: StringI):
pos = read_file(file)
solve(pos, strategy, order, output)
LEVELS: Final = {}
LEVELS[2] = ("""
2
. 1
. 1 1
1 .
""", """\
1 1
. . .
1 1
""")
LEVELS[10] = ("""
3
+.+. .
+. 0 . 2
. 1+2 1 .
2 . 0+.
.+.+.
""", """\
. . 1
. 1... | 31 |
104,976 | None | def main(oops: i64, level: i6):
board, solution = LEVELS[level]
order = DESCENDING
strategy = Done.FIRST_STRATEGY
stream: Optional[StringIO]
stream = StringIO()
board = board.strip()
expected = solution.rstrip()
range_it = range(loops)
for _ in range_it:
stream = StringIO... | 32 |
157,963 | None | def hexiom():
main(10, DEFAULT_LEVEL) # Second argument: an item of LEVELS
# --- bm_nqueens.py ---
# mypy: disallow-untyped-defs
"""Simple, brute-force N-Queens solver."""
from typing import Iterator, Iterable, Tuple, Optional
from benchmarking import benchmark
__author__ = "collinwinter@google.com (Collin W... | 33 |
119,849 | Iterator[Tuple[int, ...]] | def permutations(terable: Iterable[int], r: Optional[int] = Non):
"""permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)"""
pool = tuple(iterable)
n = len(pool)
if r is None:
r = n
indices = list(range(n))
cycles = list(range(n - r + 1, n + 1))[::-1]
yield tuple(pool[i... | 34 |
154,658 | Iterator[Tuple[int, ...]] | def do_n_queens(ueen_count: in):
"""N-Queens solver.
Args:
queen_count: the number of queens to solve for. This is also the
board size.
Yields:
Solutions to the problem. Each yielded value is looks like
(3, 8, 2, 1, 4, ..., 6) where each number is the column position f... | 35 |
150,349 | None | def bench_n_queens(ueen_count: in):
list(do_n_queens(queen_count))
@benchmark() | 36 |
81,848 | None | def nqueens():
queen_count = 8
for i in range(3):
bench_n_queens(queen_count)
# --- bm_raytrace.py ---
# mypy: disallow-untyped-defs
"""
This file contains definitions for a simple raytracer.
Copyright Callum and Tony Garnock-Jones, 2008.
This file may be freely redistributed under the MIT license,... | 37 |
27,200 | tuple[Object, float, Surface] | None | def firstIntersection( intersections: list[tuple[Object, float | None, Surface]]):
result: tuple[Object, float, Surface] | None = None
for i in intersections:
candidateT = i[1]
if candidateT is not None and candidateT > -EPSILON:
if result is None or candidateT < result[1]:
... | 38 |
84,129 | Colour | def addColours(: Colour, scale: float, b: Colou):
return (a[0] + scale * b[0],
a[1] + scale * b[1],
a[2] + scale * b[2])
class Surface:
def colourAt(self, scene: Scene, ray: Ray, p: Point, normal: Vector) -> Colour:
raise NotImplementedError
class SimpleSurface(Surface):
... | 39 |
58,019 | None | def bench_raytrace(oops: int, width: int, height: int, filename: str | Non):
range_it = range(loops)
for i in range_it:
canvas = Canvas(width, height)
s = Scene()
s.addLight(Point(30, 30, 10))
s.addLight(Point(-10, 100, 30))
s.lookAt(Point(0, 3, 0))
s.addObject(... | 40 |
88,033 | None | def raytrace():
bench_raytrace(1, DEFAULT_WIDTH, DEFAULT_HEIGHT, None)
# --- bm_richards.py ---
# mypy: disallow-untyped-defs
"""
based on a Java version:
Based on original version written in BCPL by Dr Martin Richards
in 1981 at Cambridge University Computer Laboratory, England
and a C++ version derived from... | 41 |
64,809 | None | def trace(: objec):
global layout
layout -= 1
if layout <= 0:
print()
layout = 50
print(a, end='')
TASKTABSIZE: Final = 10
class TaskWorkArea(object):
def __init__(self) -> None:
self.taskTab: List[Optional[Task]] = [None] * TASKTABSIZE
self.taskList: Optional[... | 42 |
6,158 | None | def schedule():
t = taskWorkArea.taskList
while t is not None:
if tracing:
print("tcb =", t.ident)
if t.isTaskHoldingOrWaiting():
t = t.link
else:
if tracing:
trace(chr(ord("0") + t.ident))
t = t.runTask()
class Richards... | 43 |
127,755 | None | def richards():
richards = Richards()
for i in range(3):
assert richards.run(1)
# --- bm_spectral_norm.py ---
"""
MathWorld: "Hundred-Dollar, Hundred-Digit Challenge Problems", Challenge #3.
http://mathworld.wolfram.com/Hundred-DollarHundred-DigitChallengeProblems.html
The Computer Language Benchmar... | 44 |
73,161 | float | def eval_A(: int, j: in):
return 1.0 / ((i + j) * (i + j + 1) // 2 + i + 1)
| 45 |
1,981 | List[float] | def eval_times_u(unc: Callable[[Tuple[int, List[float]]], float],
u: List[float):
return [func((i, u)) for i in xrange(len(list(u)))]
| 46 |
45,141 | List[float] | def eval_AtA_times_u(: List[float):
return eval_times_u(part_At_times_u, eval_times_u(part_A_times_u, u))
| 47 |
4,741 | float | def part_A_times_u(_u: Tuple[int, List[float]):
i, u = i_u
partial_sum: float = 0.0
for j, u_j in enumerate(u):
partial_sum += eval_A(i, j) * u_j
return partial_sum
| 48 |
1,591 | float | def part_At_times_u(_u: Tuple[int, List[float]):
i, u = i_u
partial_sum: float = 0.0
for j, u_j in enumerate(u):
partial_sum += eval_A(j, i) * u_j
return partial_sum
| 49 |
147,185 | float | def bench_spectral_norm(oops: in):
range_it = xrange(loops)
t0 = time.time()
for _ in range_it:
u: List[float] = [1] * DEFAULT_N
for dummy in xrange(10):
v = eval_AtA_times_u(u)
u = eval_AtA_times_u(v)
vBv = vv = 0.0
for ue, ve in izip(u, v):
... | 50 |
86,705 | None | def spectral_norm():
bench_spectral_norm(3)
# --- mypy_self_check.py ---
"""Mypy self check benchmark.
Type check a vendored (fixed) copy of mypy using the version of mypy
being benchmarked, compiled using the version of mypyc being benchmarked.
This can be used to track changes in both the performance of mypy... | 51 |
46,166 | None | def prepare(ypy_repo: str | Non):
assert mypy_repo
assert os.path.isdir(mypy_repo)
assert os.path.isdir(os.path.join(mypy_repo, '.git'))
if os.path.isdir(TMPDIR):
shutil.rmtree(TMPDIR)
print(f'creating venv in {os.path.abspath(VENV_DIR)}')
subprocess.run([sys.executable, '-m', 'venv',... | 52 |
28,360 | None | def mypy_self_check():
assert os.path.isdir('vendor')
env = os.environ.copy()
if 'PYTHONPATH' in env:
del env['PYTHONPATH']
if 'MYPYPATH' in env:
del env['MYPYPATH']
subprocess.run(
[
os.path.join(VENV_DIR, 'bin', 'mypy'),
'--config-file',
... | 53 |
85,178 | None | def create_attrs():
N = 40
a = [C(1, [], True)] * N
l = ['x']
for i in range(10000):
for n in range(N):
a[n] = C(n, l, False)
b = []
for n in range(N):
b.append(C2(n=n, l=l))
@benchmark() | 54 |
107,759 | None | def attrs_attr_access():
N = 40
a = []
for n in range(N):
a.append(C(n, [str(n)], n % 3 == 0))
c = 0
for i in range(100000):
for o in a:
c += o.n
c += len(o.l)
if o.b:
c -= 1
o.n ^= 1
assert c == 80600000, c
@benc... | 55 |
75,324 | None | def attrs_method():
N = 40
a = []
for n in range(N):
a.append(C(n, [str(n)], n % 3 == 0))
c = 0
for i in range(10000):
for o in a:
o.add(i & 3)
c += o.n
assert c == 3007600000, c
@attr.s(auto_attribs=True, hash=True)
class F:
n: int
s: str
@be... | 56 |
74,494 | None | def attrs_as_dict_key():
d: Dict[F, int] = {}
a = [F(i % 4, str(i % 3)) for i in range(100)]
for i in range(1000):
for f in a:
if f in d:
d[f] += 1
else:
d[f] = 1
assert len(d) == 12, len(d)
# --- builtins.py ---
"""Benchmarks for built-... | 57 |
126,819 | None | def min_max_pair():
a = []
for i in range(20):
a.append(i * 12753 % (2**15 - 1))
expected_min = min(a)
expected_max = max(a)
n = 0
for i in range(100 * 1000):
n = 1000000000
m = 0
for j in a:
n = min(n, j)
m = max(m, j)
assert n... | 58 |
61,734 | None | def min_max_sequence():
a = []
for i in range(1000):
a.append([i * 2])
a.append([i, i + 2])
a.append([i] * 15)
n = 0
for i in range(100):
for s in a:
x = min(s)
n += x
x = max(s)
n += x
assert n == 399800000, n
@benc... | 59 |
41,293 | None | def map_builtin():
a = []
for j in range(100):
for i in range(10):
a.append([i * 2])
a.append([i, i + 2])
a.append([i] * 6)
n = 0
for i in range(100):
k = 0
for lst in a:
x = list(map(inc, lst))
if k == 0:
... | 60 |
9,175 | int | def inc(: in):
return x + 1
# --- bytes.py ---
from benchmarking import benchmark
@benchmark() | 61 |
43,891 | None | def bytes_concat():
a = []
for i in range(1000):
a.append(b'Foobar-%d' % i)
a.append(b' %d str' % i)
n = 0
for i in range(1000):
for s in a:
b = b'foo' + s
if b == s:
n += 1
b += b'bar'
if b != s:
... | 62 |
121,151 | None | def bytes_methods():
"""Use a mix of bytes methods (but not split/join)."""
a = []
for i in range(1000):
a.append(b'Foobar-%d' % i)
a.append(b' %d str' % i)
n = 0
for i in range(100):
for s in a:
if s.startswith(b'foo'):
n += 1
if s.... | 63 |
177,532 | None | def bytes_format():
a = []
for i in range(1000):
a.append(b'Foobar-%d' % i)
a.append(b'%d str' % i)
n = 0
for i in range(100):
for s in a:
n += len(b"foobar %s stuff" % s)
ss = b"foobar %s stuff" % s
n += len(b"%s-%s" % (s, ss))
assert n ... | 64 |
18,009 | None | def bytes_slicing():
a = []
for i in range(1000):
a.append(b'Foobar-%d' % i)
a.append(b'%d str' % i)
n = 0
for i in range(1000):
for s in a:
n += len(s[2:-2])
if s[:3] == b'Foo':
n += 1
if s[-2:] == b'00':
n +=... | 65 |
178,042 | None | def bytes_split_and_join():
a = []
for i in range(1000):
a.append(b'Foobar-%d' % i)
a.append(b'%d-ab-asdfsdf-asdf' % i)
a.append(b'yeah')
n = 0
for i in range(100):
for s in a:
items = s.split(b'-')
if b'-'.join(items) == s:
n += 1... | 66 |
106,273 | None | def bytes_searching():
a = []
for i in range(1000):
a.append(b'Foobar-%d' % i)
a.append(b'%d-ab-asdfsdf-asdf' % i)
a.append(b'yeah')
n = 0
for i in range(100):
for s in a:
if b'i' in s:
n += 1
if s.find(b'asd') >= 0:
... | 67 |
83,077 | None | def bytes_call():
a = []
for i in range(100):
a.append([65, 55])
a.append([0, 1, 2, 3])
a.append([100])
n = 0
for i in range(10 * 1000):
for s in a:
b = bytes(s)
n += len(b)
assert n == 7000000, n
@benchmark() | 68 |
163,614 | None | def bytes_indexing():
a = []
for i in range(1000):
a.append(b'Foobar-%d' % i)
a.append(b'%d-ab-asdfsdf-asdf' % i)
a.append(b'yeah')
n = 0
for i in range(100):
for s in a:
for j in range(len(s)):
if s[j] == 97:
n += 1
as... | 69 |
49,957 | None | def nested_func():
n = 0
for i in range(100 * 1000):
n += call_nested_fast()
assert n == 5500000, n
| 70 |
176,065 | int | def call_nested_fast():
n = 0
def add(d: int) -> None:
nonlocal n
n += d
for i in range(10):
add(i)
n += 1
return n
@benchmark() | 71 |
119,177 | None | def nested_func_escape():
n = 0
for i in range(100 * 1000):
n = nested_func_inner(n)
assert n == 300000, n
| 72 |
94,694 | int | def nested_func_inner(: in):
def add(d: int) -> None:
nonlocal n
n += d
invoke(add)
return n
| 73 |
62,371 | None | def invoke(: Callable[[int], None):
for i in range(3):
f(i)
@benchmark() | 74 |
71,547 | None | def method_object():
a = []
for i in range(5):
a.append(Adder(i))
a.append(Adder2(i))
n = 0
for i in range(100 * 1000):
for adder in a:
n = adjust(n, adder.add)
assert n == 7500000, n
| 75 |
159,936 | int | def adjust(: int, add: Callable[[int], int):
for i in range(3):
n = add(n)
return n
class Adder:
def __init__(self, n: int) -> None:
self.n = n
def add(self, x: int) -> int:
return self.n + x
class Adder2(Adder):
def add(self, x: int) -> int:
return self.n + x +... | 76 |
135,596 | None | def create_dataclass():
N = 40
a = [C(1, [], True)] * N
l = ['x']
for i in range(10000):
for n in range(N):
a[n] = C(n, l, False)
b = []
for n in range(N):
b.append(C2(n=n, l=l))
@benchmark() | 77 |
126,303 | None | def dataclass_attr_access():
N = 40
a = []
for n in range(N):
a.append(C(n, [str(n)], n % 3 == 0))
c = 0
for i in range(100000):
for o in a:
c += o.n
c += len(o.l)
if o.b:
c -= 1
o.n ^= 1
assert c == 80600000, c
@... | 78 |
45,165 | None | def dataclass_method():
N = 40
a = []
for n in range(N):
a.append(C(n, [str(n)], n % 3 == 0))
c = 0
for i in range(10000):
for o in a:
o.add(i & 3)
c += o.n
assert c == 3007600000, c
@dataclass(frozen=True)
class F:
n: int
s: str
@benchmark() | 79 |
15,796 | None | def dataclass_as_dict_key():
d: Dict[F, int] = {}
a = [F(i % 4, str(i % 3)) for i in range(100)]
for i in range(1000):
for f in a:
if f in d:
d[f] += 1
else:
d[f] = 1
assert len(d) == 12, len(d)
# --- dicts.py ---
from typing import List... | 80 |
72,037 | None | def dict_iteration():
a = []
for j in range(1000):
d = {}
for i in range(j % 10):
d['Foobar-%d' % j] = j
d['%d str' % j] = i
a.append(d)
n = 0
for i in range(1000):
for d in a:
for k in d:
if k == '0 str':
... | 81 |
45,159 | None | def dict_to_list():
a = []
for j in range(1000):
d = {}
for i in range(j % 10):
d['Foobar-%d' % j] = j
d['%d str' % j] = i
a.append(d)
n = 0
for i in range(1000):
for d in a:
n ++ len(list(d))
n += len(list(d.keys()))
... | 82 |
147,939 | None | def dict_set_default():
n = 0
for i in range(100 * 1000):
d: Dict[int, List[int]] = {}
for j in range(i % 10):
for k in range(i % 11):
d.setdefault(j, []).append(k)
n += len(d)
assert n == 409095, n
@benchmark() | 83 |
152,033 | None | def dict_clear():
n = 0
for i in range(1000 * 1000):
d = {}
for j in range(i % 4):
d[j] = 'x'
d.clear()
assert len(d) == 0
@benchmark() | 84 |
13,686 | None | def dict_copy():
a = []
for j in range(100):
d = {}
for i in range(j % 10):
d['Foobar-%d' % j] = j
d['%d str' % j] = i
a.append(d)
n = 0
for i in range(10 * 1000):
for d in a:
d2 = d.copy()
d3 = d2.copy()
d4 = ... | 85 |
30,596 | None | def dict_call_keywords():
n = 0
for i in range(1000 * 1000):
d = dict(id=5, name="dummy", things=[])
n += len(d)
assert n == 3000000, n
@benchmark() | 86 |
30,653 | None | def dict_call_generator():
a = []
for j in range(1000):
items = [
('Foobar-%d' % j, j),
('%d str' % j, 'x'),
]
if j % 2 == 0:
items.append(('blah', 'bar'))
a.append(items)
n = 0
for i in range(1000):
for s in a:
d ... | 87 |
105,762 | None | def dict_del_item():
d = {'long_lived': 'value'}
for j in range(1000 * 1000):
d['xyz'] = 'asdf'
d['asdf'] = 'lulz'
del d['xyz']
d['foobar'] = 'baz zar'
del d['foobar']
del d['asdf']
# --- enums.py ---
from enum import Enum
from benchmarking import benchmark
c... | 88 |
89,422 | None | def enums():
a = [MyEnum.A, MyEnum.B, MyEnum.C] * 10
n = 0
for i in range(100000):
for x in a:
if x is MyEnum.A:
n += 1
elif x is MyEnum.B:
n += 2
assert n == 3000000, n
# --- exceptions.py ---
from benchmarking import benchmark
@bench... | 89 |
98,687 | None | def catch_exceptions():
n = 0
for i in range(100 * 1000):
try:
f(i)
except ValueError:
n += 1
assert n == 35714, n
| 90 |
42,350 | None | def f(: in):
if i % 4 == 0:
raise ValueError("problem")
else:
g(i)
| 91 |
131,791 | None | def g(: in):
if i % 7 == 0:
raise ValueError
# --- files.py ---
"""Benchmarks for file-like objects."""
import os
from benchmarking import benchmark
@benchmark() | 92 |
123,470 | None | def read_write_text():
a = []
for i in range(1000):
a.append('Foobar-%d\n' % i)
a.append(('%d-ab-asdfsdf-asdf' % i) * 2)
a.append('yeah\n')
a.append('\n')
joined = ''.join(a)
fnam = '__dummy.txt'
try:
for i in range(100):
with open(fnam, 'w') as f... | 93 |
99,991 | None | def readline():
a = []
for i in range(1000):
a.append('Foobar-%d\n' % i)
a.append(('%d-ab-asdfsdf-asdf' % i) * 2 + '\n')
a.append('yeah\n')
a.append('\n')
fnam = '__dummy.txt'
try:
for i in range(50):
with open(fnam, 'w') as f:
for s i... | 94 |
104,283 | None | def read_write_binary():
a = []
for i in range(1000):
a.append(b'Foobar-%d\n' % i)
a.append((b'%d-ab-asdfsdf-asdf' % i) * 2)
a.append(b'yeah\n')
a.append(b'\n')
joined = b''.join(a)
fnam = '__dummy.txt'
try:
for i in range(100):
with open(fnam, 'w... | 95 |
147,147 | None | def read_write_binary_chunks():
a = []
for i in range(500):
a.append(b'Foobar-%d\n' % i)
a.append((b'%d-ab-asdfsdf-asdf' % i) * 2)
a.append(b'yeah\n')
a.append(b'\n')
joined = b''.join(a)
i = 0
size = 2048
chunks = []
while i < len(joined):
chunks.app... | 96 |
141,449 | None | def read_write_chars():
fnam = '__dummy.txt'
try:
for i in range(200):
with open(fnam, 'w') as f:
for s in range(1000):
f.write('a')
f.write('b')
f.write('c')
n = 0
with open(fnam) as f:
... | 97 |
200 | None | def read_write_small_files():
fnam = '__dummy%d.txt'
num_files = 10
try:
for i in range(500):
for i in range(num_files):
with open(fnam % i, 'w') as f:
f.write('yeah\n')
for i in range(num_files):
with open(fnam % i) as f:
... | 98 |
183,429 | None | def read_write_close():
fnam = '__dummy%d.txt'
num_files = 10
try:
for i in range(500):
for i in range(num_files):
f = open(fnam % i, 'w')
f.write('yeah\n')
f.close()
for i in range(num_files):
f = open(fnam % i... | 99 |
End of preview. Expand in Data Studio
No dataset card yet
- Downloads last month
- 20