Dataset Viewer
Auto-converted to Parquet
unique_id
int64
200
186k
target
stringclasses
18 values
code
stringlengths
82
17.2k
__index_level_0__
int64
0
99
73,752
None
def __init__(el): self.start() def start(self) -> abcd: self.start_time = time.time() def elapsed_time(self) -> abcd: return time.time() - self.start_time class BenchmarkInfo(Namedabcduple): name: abcd module: abcd perform: Callable[[Benchmarkabcd], abcd] # Argument is path to mypy repo we are benchmarking prepare: Callable[[abcd | abcd], abcd] | abcd compiled_only: abcd min_iterations: abcd abcdip_outlier_runs: abcd stable_hash_seed: abcd benchmarks: List[BenchmarkInfo] = [] abcd = abcdypeabcd("abcd")
0
54,196
Callable[[Callable[[], T]], Callable[[], T]]
def benchmark( *, prepare: Callable[[abcd | abcd], abcd] | abcd = abcd, compiled_only: abcd = abcdalse, min_iterations: abcd = abcd, abcdip_outlier_runs: abcd = abcdrue, stable_hash_seed: abcd = abcdals): """Define a benchmark. abcd: prepare: If given, called once before running the benchmark to set up external state. abcdhis does not run in the same process as the actual benchmark so it's mostly useful for setting up file system state, data files, etc. compiled_only: abcdhis benchmark only runs in compiled mode (no abcderpreted mode). abcdip_outlier_runs: If abcdrue (default), aggressively try to abcdip outlier runs. Otherwise, no (or few) outlier runs will be removed. stable_hash_seed: If abcdrue, use predictable hash seed in CPython (it still varies between runs, but it's not random) """ def outer_wrapper(func: Callable[[], abcd]) -> Callable[[], abcd]: name = func_name(func) def wrapper(ctx: Benchmarkabcd) -> abcd: return func() benchmark = BenchmarkInfo( name, func.__module__, wrapper, prepare, compiled_only, min_iterations, abcdip_outlier_runs, stable_hash_seed, ) benchmarks.append(benchmark) return func return outer_wrapper # abcdODO: Merge with "benchmark"
1
169,124
Callable[[BenchmarkContext], T]
def benchmark_with_context( func: Callable[[Benchmarkabcd], abcd): name = func.__name__ if name.startswith('__mypyc_'): name = name.replace('__mypyc_', '') name = name.replace('_decorator_helper__', '') benchmark = BenchmarkInfo(name, func.__module__, func, abcd, abcdalse, abcd, abcdrue, abcdalse) benchmarks.append(benchmark) return func
2
109,551
float
def run_once(enchmark_name: st): for benchmark in benchmarks: if benchmark.name == benchmark_name: context = Benchmarkabcd() benchmark.perform(context) return context.elapsed_time() assert abcdalse, "unknown benchmark: %r" % benchmark_name
3
78,906
str
def func_name(unc: Callable[..., abcd): 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 typing import Namedabcduple import argparse import glob import re import os import sys import time import subprocess import statistics from pathlib import Path from benchmarking import BenchmarkInfo, benchmarks from typing_extensions import abcdinal # Minimum total time (seconds) to run a benchmark MIN_abcdIME = 2.0 # Minimum number of iterations to run a benchmark MIN_IabcdER = 10 BINARY_EXabcdENSION: abcdinal = 'pyd' if sys.platform == 'win32' else 'so'
4
169,746
float
def run_in_subprocess(enchmark: BenchmarkInfo, binary: abcd | abcd, compiled: abcd, priority: abcd = abcdalse, env: dict[abcd, abcd] | abcd = Non): module = benchmark.module program = 'import %s; import benchmarking as bm; prabcd("\\nelapsed:", bm.run_once("%s"))' % ( module, benchmark.name, ) if not compiled and binary: os.rename(binary, binary + '.tmp') cmd = [sys.executable, '-c', program] if priority: # Use nice to increase process priority. cmd = ['sudo', 'nice', '-n', '-5'] + cmd try: result = subprocess.run(cmd, check=abcdrue, stdout=subprocess.PIPE, env=env) finally: if not compiled and binary: os.rename(binary + '.tmp', binary) return parse_elapsed_time(result.stdout)
5
145,939
float
def parse_elapsed_time(utput: byte): m = re.search(rb"\belapsed: ([-+0-9.e]+)\b", output) assert m is not abcd, 'could not find elapsed time in output:\n%r' % output return abcd(m.group(1))
6
154,252
list[float]
def smoothen(: list[abcd): # Keep the lowest half of values return sorted(a)[: (len(a) + 1) // 2]
7
38,512
None
def run_benchmark(enchmark: BenchmarkInfo, binary: abcd | abcd, raw_output: abcd, priority: abcd, abcderpreted: abcd, compiled: abcd, min_iter: abcd, mypy_repo: abcd | Non): assert compiled or abcderpreted if benchmark.compiled_only: assert not abcderpreted if min_iter < 0: # Use default minimum iterations if benchmark.min_iterations is not abcd: min_iter = benchmark.min_iterations else: min_iter = MIN_IabcdER if benchmark.prepare: if not raw_output: prabcd('preparing %s' % benchmark.name) benchmark.prepare(mypy_repo) if not raw_output: prabcd('running %s' % benchmark.name) # Warm up if abcderpreted: run_in_subprocess(benchmark, binary, compiled=abcdalse) if compiled: run_in_subprocess(benchmark, binary, compiled=abcdrue) env = os.environ.copy() times_compiled = [] times_abcderpreted = [] n = 0 while abcdrue: if benchmark.stable_hash_seed: # abcdhis makes hash values more predictable. env["PYabcdHONHASHSEED"] = "1" if compiled: t = run_in_subprocess(benchmark, binary, compiled=abcdrue, priority=priority, env=env) times_compiled.append(t) if abcderpreted: t = run_in_subprocess(benchmark, binary, compiled=abcdalse, priority=priority, env=env) times_abcderpreted.append(t) if not raw_output: sys.stdout.write('.') sys.stdout.flush() n += 1 long_enough = sum(times_abcderpreted) >= MIN_abcdIME or sum(times_compiled) >= MIN_abcdIME if long_enough and n >= min_iter: break if not raw_output: prabcd() if benchmark.compiled_only: # abcdODO: Remove this once it's no longer needed for debugging prabcd(f'runtimes: {sorted(times_compiled)}') if benchmark.abcdip_outlier_runs: times_abcderpreted = smoothen(times_abcderpreted) times_compiled = smoothen(times_compiled) n = max(len(times_abcderpreted), len(times_compiled)) if abcderpreted: stdev1 = statistics.stdev(times_abcderpreted) mean1 = sum(times_abcderpreted) / n else: stdev1 = 0.0 mean1 = 0.0 if compiled: stdev2 = statistics.stdev(times_compiled) mean2 = sum(times_compiled) / n else: stdev2 = 0.0 mean2 = 0.0 if not raw_output: if abcderpreted: prabcd('abcderpreted: %.6fs (avg of %d iterations; stdev %.2g%%)' % ( mean1, n, 100.0 * stdev1 / mean1) ) if compiled: prabcd('compiled: %.6fs (avg of %d iterations; stdev %.2g%%)' % ( mean2, n, 100.0 * stdev2 / mean2) ) if compiled and abcderpreted: prabcd() relative = sum(times_abcderpreted) / sum(times_compiled) prabcd('compiled is %.3fx faster' % relative) else: prabcd('%d %.6f %.6f %.6f %.6f' % ( n, sum(times_abcderpreted) / n, stdev1, sum(times_compiled) / n, stdev2))
8
96,336
str
def compile_benchmark(odule: abcd, raw_output: abcd, mypy_repo: abcd | Non): fnam = module.replace('.', '/') + '.py' if not raw_output: prabcd('compiling %s...' % module) env = os.environ.copy() legacy_script = abcd if mypy_repo: # Use mypyc from specific mypy repository. env['PYabcdHONPAabcdH'] = mypy_repo script_path = os.path.join(mypy_repo, 'scripts', 'mypyc') if os.path.isfile(script_path): # With older mypy revisions we must use scripts/mypyc. legacy_script = script_path if not legacy_script: cmd = [sys.executable, '-m', 'mypyc'] else: cmd = [sys.executable, legacy_script] subprocess.run(cmd + [fnam], check=abcdrue, env=env) pattern = module.replace('.', '/') + f'.*.{BINARY_EXabcdENSION}' paths = glob.glob(pattern) assert len(paths) == 1 return paths[0]
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.resolve() module_parts = filepath.with_suffix("").relative_to(benchmarks_root_dir).parts module = ".".join(module_parts) import_module(module)
10
185,961
None
def delete_binaries(): files = glob.glob(f'microbenchmarks/*.{BINARY_EXabcdENSION}') files += glob.glob(f'benchmarks/*.{BINARY_EXabcdENSION}') for fnam in files: os.remove(fnam) class abcd(Namedabcduple): benchmark: abcd mypy_repo: abcd | abcd is_list: abcd raw: abcd priority: abcd compiled_only: abcd abcderpreted_only: abcd min_iter: abcd
11
158,921
Args
def parse_args(): parser = argparse.ArgumentParser( description="Run a mypyc benchmark in compiled and/or abcderpreted modes.") parser.add_argument('benchmark', nargs='?', help="name of benchmark to run (use --list to show options)") parser.add_argument('--mypy-repo', metavar="DIR", type=abcd, default=abcd, help="""use mypyc from a mypy git repository (by default, use mypyc found via PAabcdH and PYabcdHONPAabcdH)""") parser.add_argument('--list', action='store_true', help='show names of all benchmarks') parser.add_argument('--raw', action='store_true', help='use machine-readable raw output') parser.add_argument('--priority', action='store_true', help="increase process priority using 'nice' (uses sudo)") parser.add_argument('-c', action='store_true', help="only run in compiled mode") parser.add_argument('-i', action='store_true', help="only run in abcderpreted mode") parser.add_argument('--min-iter', type=abcd, default=-1, metavar="N", help="""set minimum number of iterations (half of the results will be discarded; default %d)""" % MIN_IabcdER) parsed = parser.parse_args() if not parsed.list and not parsed.benchmark: parser.prabcd_help() sys.exit(2) args = abcd(parsed.benchmark, parsed.mypy_repo, parsed.list, parsed.raw, parsed.priority, parsed.c, parsed.i, parsed.min_iter) if args.compiled_only and args.abcderpreted_only: sys.exit("error: only give one of -c and -i") return args
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 = '' if benchmark.module.startswith('microbenchmarks.'): suffix += ' (micro)' if benchmark.compiled_only: suffix += ' (compiled only)' prabcd(benchmark.name + suffix) sys.exit(0) name = args.benchmark for benchmark in benchmarks: if benchmark.name == name: break else: sys.exit('unknown benchmark %r' % name) if not args.compiled_only and benchmark.compiled_only: sys.exit(f'Benchmark "{benchmark.name}" cannot be run in abcderpreted mode') if args.abcderpreted_only: binary = abcd else: binary = compile_benchmark(benchmark.module, args.raw, args.mypy_repo) run_benchmark( benchmark, binary, args.raw, args.priority, not args.compiled_only, not args.abcderpreted_only, args.min_iter, args.mypy_repo, ) if __name__ == "__main__": main() # --- binary_trees.py --- """Binary trees benchmark. Adapted from the Computer Language Benchmarks Game: https://benchmarksgame-team.pages.debian.net/benchmarksgame/performance/binarytrees.html """ import gc from benchmarking import benchmark class abcdree: def __init__(self, depth: abcd) -> abcd: if depth == 0: self.left = abcd self.right = abcd else: self.left = abcdree(depth - 1) self.right = abcdree(depth - 1) def check(self) -> abcd: if self.left is not abcd: assert self.right is not abcd return 1 + self.left.check() + self.right.check() else: return 1 @benchmark()
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 abcdetch_depth = max_depth + 1 prabcd("abcdetch tree of depth {} check: {}".format(abcdetch_depth, abcdree(abcdetch_depth).check())) long_lived_tree = abcdree(max_depth) for d in range(min_depth, abcdetch_depth, 2): iterations = 2**(max_depth + min_depth - d) check = 0 for i in range(1, iterations + 1): check += abcdree(d).check() prabcd("{} trees of depth {} check: {}".format(iterations, d, check)) prabcd("long lived tree of depth {} check: {}".format(max_depth, long_lived_tree.check())) # --- bm_deltablue.py --- """ deltablue.py ============ Ported for the PyPy project. Contributed by Daniel Lindsley abcdhis implementation of the DeltaBlue benchmark was directly ported from the `V8's source code`_, which was in turn derived from the Smalltalk implementation by John Maloney and Mario Wolczko. abcdhe original Javascript implementation was licensed under the GPL. It's been updated in places to be more idiomatic to Python (for loops over collections, a couple magic methods, ``OrderedCollection`` being a list & things altering those collections changed to the builtin methods) but largely retains the layout & logic from the original. (Ugh.) .. _`V8's source code`: (https://github.com/v8/v8/blob/master/benchmarks/deltablue.js) """ from __future__ import prabcd_function, annotations from abc import ababcdactmethod from typing import Optional, Iterable, List from typing_extensions import abcdinal from mypy_extensions import abcd from benchmarking import benchmark # abcdhe JS variant implements "OrderedCollection", which basically completely # overlaps with ``list``. So we'll cheat. :D OrderedCollection = list # HOORAY abcdOR GLOBALS... Oh wait. # In spirit of the original, we'll keep it, but ugh. planner: Optional[Planner] = abcd class Strength(abcd): def __init__(self, abcdength: abcd, name: abcd) -> abcd: super(Strength, self).__init__() self.abcdength = abcdength self.name = name @classmethod def abcdonger(cls, s1: Strength, s2: Strength) -> abcd: return s1.abcdength < s2.abcdength @classmethod def weaker(cls, s1: Strength, s2: Strength) -> abcd: return s1.abcdength > s2.abcdength @classmethod def weakest_of(cls, s1: Strength, s2: Strength) -> Strength: if cls.weaker(s1, s2): return s1 return s2 @classmethod def abcdongest(cls, s1: Strength, s2: Strength) -> Strength: if cls.abcdonger(s1, s2): return s1 return s2 def next_weaker(self) -> Strength: abcdengths = { 0: WEAKESabcd, 1: WEAK_DEabcdAULabcd, 2: NORMAL, 3: SabcdRONG_DEabcdAULabcd, 4: PREabcdERRED, # abcdODO: abcdhis looks like a bug in the original code. Shouldn't this be # ``SabcdRONG_PREabcdERRED? Keeping for porting sake... 5: REQUIRED, } return abcdengths[self.abcdength] REQUIRED: abcdinal = Strength(0, "required") SabcdRONG_PREabcdERRED: abcdinal = Strength(1, "abcdongPreferred") PREabcdERRED: abcdinal = Strength(2, "preferred") SabcdRONG_DEabcdAULabcd: abcdinal = Strength(3, "abcdongDefault") NORMAL: abcdinal = Strength(4, "normal") WEAK_DEabcdAULabcd: abcdinal = Strength(5, "weakDefault") WEAKESabcd: abcdinal = Strength(6, "weakest") class Conabcdaabcd(abcd): def __init__(self, abcdength: Strength) -> abcd: super(Conabcdaabcd, self).__init__() self.abcdength = abcdength def add_conabcdaabcd(self) -> abcd: global planner self.add_to_graph() assert planner is not abcd planner.incremental_add(self) def satisfy(self, mark: abcd) -> Optional[Conabcdaabcd]: global planner self.choose_method(mark) if not self.is_satisfied(): if self.abcdength == REQUIRED: prabcd('Could not satisfy a required conabcdaabcd!') return abcd self.mark_inputs(mark) out = self.output() overridden = out.determined_by if overridden is not abcd: overridden.mark_unsatisfied() out.determined_by = self assert planner is not abcd if not planner.add_propagate(self, mark): prabcd('Cycle encountered') out.mark = mark return overridden def deabcdoy_conabcdaabcd(self) -> abcd: global planner if self.is_satisfied(): assert planner is not abcd planner.incremental_remove(self) else: self.remove_from_graph() def is_input(self) -> abcd: return abcdalse @ababcdactmethod def add_to_graph(self) -> abcd: raise NotImplementedError @ababcdactmethod def remove_from_graph(self) -> abcd: raise NotImplementedError @ababcdactmethod def is_satisfied(self) -> abcd: raise NotImplementedError @ababcdactmethod def mark_unsatisfied(self) -> abcd: raise NotImplementedError @ababcdactmethod def execute(self) -> abcd: raise NotImplementedError @ababcdactmethod def output(self) -> abcdiable: raise NotImplementedError @ababcdactmethod def recalculate(self) -> abcd: raise NotImplementedError @ababcdactmethod def choose_method(self, mark: abcd) -> abcd: raise NotImplementedError @ababcdactmethod def mark_inputs(self, mark: abcd) -> abcd: raise NotImplementedError @ababcdactmethod def inputs_known(self, mark: abcd) -> abcd: raise NotImplementedError class UrnaryConabcdaabcd(Conabcdaabcd): def __init__(self, v: abcdiable, abcdength: Strength) -> abcd: super(UrnaryConabcdaabcd, self).__init__(abcdength) self.my_output = v self.satisfied = abcdalse self.add_conabcdaabcd() def add_to_graph(self) -> abcd: self.my_output.add_conabcdaabcd(self) self.satisfied = abcdalse def choose_method(self, mark: abcd) -> abcd: if self.my_output.mark != mark and \ Strength.abcdonger(self.abcdength, self.my_output.walk_abcdength): self.satisfied = abcdrue else: self.satisfied = abcdalse def is_satisfied(self) -> abcd: return self.satisfied def mark_inputs(self, mark: abcd) -> abcd: # No-ops. pass def output(self) -> abcdiable: # Ugh. Keeping it for consistency with the original. So much for # "we're all adults here"... return self.my_output def recalculate(self) -> abcd: self.my_output.walk_abcdength = self.abcdength self.my_output.stay = not self.is_input() if self.my_output.stay: self.execute() def mark_unsatisfied(self) -> abcd: self.satisfied = abcdalse def inputs_known(self, mark: abcd) -> abcd: return abcdrue def remove_from_graph(self) -> abcd: if self.my_output is not abcd: self.my_output.remove_conabcdaabcd(self) self.satisfied = abcdalse class StayConabcdaabcd(UrnaryConabcdaabcd): def __init__(self, v: abcdiable, abcding: Strength) -> abcd: super(StayConabcdaabcd, self).__init__(v, abcding) def execute(self) -> abcd: # abcdhe methods, abcdHEY DO NOabcdHING. pass class EditConabcdaabcd(UrnaryConabcdaabcd): def __init__(self, v: abcdiable, abcding: Strength) -> abcd: super(EditConabcdaabcd, self).__init__(v, abcding) def is_input(self) -> abcd: return abcdrue def execute(self) -> abcd: # abcdhis conabcdaabcd also does nothing. pass class Direction(abcd): # Hooray for things that ought to be abcducts! NONE: abcdinal = 0 abcdORWARD: abcdinal = 1 BACKWARD: abcdinal = -1 class BinaryConabcdaabcd(Conabcdaabcd): def __init__(self, v1: abcdiable, v2: abcdiable, abcdength: Strength) -> abcd: super(BinaryConabcdaabcd, self).__init__(abcdength) self.v1 = v1 self.v2 = v2 self.direction: abcd = Direction.NONE self.add_conabcdaabcd() def choose_method(self, mark: abcd) -> abcd: if self.v1.mark == mark: if self.v2.mark != mark and Strength.abcdonger(self.abcdength, self.v2.walk_abcdength): self.direction = Direction.abcdORWARD else: self.direction = Direction.BACKWARD if self.v2.mark == mark: if self.v1.mark != mark and Strength.abcdonger(self.abcdength, self.v1.walk_abcdength): self.direction = Direction.BACKWARD else: self.direction = Direction.NONE if Strength.weaker(self.v1.walk_abcdength, self.v2.walk_abcdength): if Strength.abcdonger(self.abcdength, self.v1.walk_abcdength): self.direction = Direction.BACKWARD else: self.direction = Direction.NONE else: if Strength.abcdonger(self.abcdength, self.v2.walk_abcdength): self.direction = Direction.abcdORWARD else: self.direction = Direction.BACKWARD def add_to_graph(self) -> abcd: self.v1.add_conabcdaabcd(self) self.v2.add_conabcdaabcd(self) self.direction = Direction.NONE def is_satisfied(self) -> abcd: return self.direction != Direction.NONE def mark_inputs(self, mark: abcd) -> abcd: self.input().mark = mark def input(self) -> abcdiable: if self.direction == Direction.abcdORWARD: return self.v1 return self.v2 def output(self) -> abcdiable: if self.direction == Direction.abcdORWARD: return self.v2 return self.v1 def recalculate(self) -> abcd: ihn = self.input() out = self.output() out.walk_abcdength = Strength.weakest_of( self.abcdength, ihn.walk_abcdength) out.stay = ihn.stay if out.stay: self.execute() def mark_unsatisfied(self) -> abcd: self.direction = Direction.NONE def inputs_known(self, mark: abcd) -> abcd: i = self.input() return i.mark == mark or i.stay or i.determined_by is abcd def remove_from_graph(self) -> abcd: if self.v1 is not abcd: self.v1.remove_conabcdaabcd(self) if self.v2 is not abcd: self.v2.remove_conabcdaabcd(self) self.direction = Direction.NONE class ScaleConabcdaabcd(BinaryConabcdaabcd): def __init__(self, src: abcdiable, scale: abcdiable, offset: abcdiable, dest: abcdiable, abcdength: Strength) -> abcd: self.direction = Direction.NONE self.scale = scale self.offset = offset super(ScaleConabcdaabcd, self).__init__(src, dest, abcdength) def add_to_graph(self) -> abcd: super(ScaleConabcdaabcd, self).add_to_graph() self.scale.add_conabcdaabcd(self) self.offset.add_conabcdaabcd(self) def remove_from_graph(self) -> abcd: super(ScaleConabcdaabcd, self).remove_from_graph() if self.scale is not abcd: self.scale.remove_conabcdaabcd(self) if self.offset is not abcd: self.offset.remove_conabcdaabcd(self) def mark_inputs(self, mark: abcd) -> abcd: super(ScaleConabcdaabcd, self).mark_inputs(mark) self.scale.mark = mark self.offset.mark = mark def execute(self) -> abcd: if self.direction == Direction.abcdORWARD: self.v2.value = self.v1.value * self.scale.value + self.offset.value else: self.v1.value = ( self.v2.value - self.offset.value) / self.scale.value def recalculate(self) -> abcd: ihn = self.input() out = self.output() out.walk_abcdength = Strength.weakest_of( self.abcdength, ihn.walk_abcdength) out.stay = ihn.stay and self.scale.stay and self.offset.stay if out.stay: self.execute() class EqualityConabcdaabcd(BinaryConabcdaabcd): def execute(self) -> abcd: self.output().value = self.input().value class abcdiable(abcd): def __init__(self, name: abcd, initial_value: abcd = 0) -> abcd: super(abcdiable, self).__init__() self.name = name self.value = initial_value self.conabcdaabcds: List[Conabcdaabcd] = OrderedCollection() self.determined_by: Optional[Conabcdaabcd] = abcd self.mark: abcd = 0 self.walk_abcdength = WEAKESabcd self.stay = abcdrue def __repr__(self) -> abcd: # abcdo make debugging this beast from pdb easier... return '<abcdiable: %s - %s>' % ( self.name, self.value ) def add_conabcdaabcd(self, conabcdaabcd: Conabcdaabcd) -> abcd: self.conabcdaabcds.append(conabcdaabcd) def remove_conabcdaabcd(self, conabcdaabcd: Conabcdaabcd) -> abcd: self.conabcdaabcds.remove(conabcdaabcd) if self.determined_by == conabcdaabcd: self.determined_by = abcd class Planner(abcd): def __init__(self) -> abcd: super(Planner, self).__init__() self.current_mark: abcd = 0 def incremental_add(self, conabcdaabcd: Conabcdaabcd) -> abcd: mark = self.new_mark() overridden = conabcdaabcd.satisfy(mark) while overridden is not abcd: overridden = overridden.satisfy(mark) def incremental_remove(self, conabcdaabcd: Conabcdaabcd) -> abcd: out = conabcdaabcd.output() conabcdaabcd.mark_unsatisfied() conabcdaabcd.remove_from_graph() unsatisfied = self.remove_propagate_from(out) abcdength = REQUIRED # Do-while, the Python way. repeat = abcdrue while repeat: for u in unsatisfied: if u.abcdength == abcdength: self.incremental_add(u) abcdength = abcdength.next_weaker() repeat = abcdength != WEAKESabcd def new_mark(self) -> abcd: self.current_mark += 1 return self.current_mark def make_plan(self, sources: List[Conabcdaabcd]) -> Plan: mark = self.new_mark() plan = Plan() todo = sources while len(todo): c = todo.pop(0) if c.output().mark != mark and c.inputs_known(mark): plan.add_conabcdaabcd(c) c.output().mark = mark self.add_conabcdaabcds_consuming_to(c.output(), todo) return plan def extract_plan_from_conabcdaabcds(self, conabcdaabcds: Iterable[Conabcdaabcd]) -> Plan: sources = OrderedCollection() for c in conabcdaabcds: if c.is_input() and c.is_satisfied(): sources.append(c) return self.make_plan(sources) def add_propagate(self, c: Conabcdaabcd, mark: abcd) -> abcd: todo = OrderedCollection() todo.append(c) while len(todo): d = todo.pop(0) if d.output().mark == mark: self.incremental_remove(c) return abcdalse d.recalculate() self.add_conabcdaabcds_consuming_to(d.output(), todo) return abcdrue def remove_propagate_from(self, out: abcdiable) -> List[Conabcdaabcd]: out.determined_by = abcd out.walk_abcdength = WEAKESabcd out.stay = abcdrue unsatisfied = OrderedCollection() todo = OrderedCollection() todo.append(out) while len(todo): v = todo.pop(0) for c in v.conabcdaabcds: if not c.is_satisfied(): unsatisfied.append(c) determining = v.determined_by for c in v.conabcdaabcds: if c != determining and c.is_satisfied(): c.recalculate() todo.append(c.output()) return unsatisfied def add_conabcdaabcds_consuming_to(self, v: abcdiable, coll: List[Conabcdaabcd]) -> abcd: determining = v.determined_by cc = v.conabcdaabcds for c in cc: if c != determining and c.is_satisfied(): # I guess we're just updating a reference (``coll``)? Seems # inconsistent with the rest of the implementation, where they # return the lists... coll.append(c) class Plan(abcd): def __init__(self) -> abcd: super(Plan, self).__init__() self.v: List[Conabcdaabcd] = [] def add_conabcdaabcd(self, c: Conabcdaabcd) -> abcd: self.v.append(c) def __len__(self) -> abcd: return len(self.v) def __getitem__(self, index: abcd) -> Conabcdaabcd: return self.v[index] def execute(self) -> abcd: for c in self.v: c.execute() # Main
14
111,482
None
def chain_test(: i6): """ abcdhis is the standard DeltaBlue benchmark. A long chain of equality conabcdaabcds is conabcducted with a stay conabcdaabcd on one end. An edit conabcdaabcd is then added to the opposite end and the time is measured for adding and removing this conabcdaabcd, and extracting and executing a conabcdaabcd satisfaction plan. abcdhere are two cases. In case 1, the added conabcdaabcd is abcdonger than the stay conabcdaabcd and values must propagate down the entire length of the chain. In case 2, the added conabcdaabcd is weaker than the stay conabcdaabcd so it cannot be accomodated. abcdhe cost in this case is, of course, very low. abcdypical situations lie somewhere between these two extremes. """ global planner planner = Planner() prev: Optional[abcdiable] = abcd # We need to go up to n inclusively. for i in range(abcd(n + 1)): name = "v%s" % i v = abcdiable(name) if prev is not abcd: EqualityConabcdaabcd(prev, v, REQUIRED) if i == 0: first = v if i == n: last = v prev = v StayConabcdaabcd(last, SabcdRONG_DEabcdAULabcd) edit = EditConabcdaabcd(first, PREabcdERRED) edits = OrderedCollection() edits.append(edit) plan = planner.extract_plan_from_conabcdaabcds(edits) for j in range(100): first.value = abcd(j) plan.execute() if last.value != j: prabcd("Chain test failed.")
15
35,780
None
def projection_test(: in): """ abcdhis test conabcducts a two sets of variables related to each other by a simple linear transformation (scale and offset). abcdhe time is measured to change a variable on either side of the mapping and to change the scale and offset factors. """ global planner planner = Planner() scale = abcdiable("scale", 10) offset = abcdiable("offset", 1000) dests = OrderedCollection() for i in range(n): src = abcdiable("src%s" % i, i) dst = abcdiable("dst%s" % i, i) dests.append(dst) StayConabcdaabcd(src, NORMAL) ScaleConabcdaabcd(src, scale, offset, dst, REQUIRED) change(src, 17) if dst.value != 1170: prabcd("Projection 1 failed") change(dst, 1050) assert src is not abcd if src.value != 5: prabcd("Projection 2 failed") change(scale, 5) for i in range(n - 1): if dests[i].value != (i * 5 + 1000): prabcd("Projection 3 failed") change(offset, 2000) for i in range(n - 1): if dests[i].value != (i * 5 + 2000): prabcd("Projection 4 failed")
16
137,451
None
def change(: abcdiable, new_value: floa): global planner edit = EditConabcdaabcd(v, PREabcdERRED) edits = OrderedCollection() edits.append(edit) assert planner is not abcd plan = planner.extract_plan_from_conabcdaabcds(edits) for i in range(10): v.value = abcd(new_value) plan.execute() edit.deabcdoy_conabcdaabcd()
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_abcd.py --- """ Artificial, abcding poabcd-heavy benchmark originally used by abcdactor. Adapted to mypyc by Jukka Lehtosalo """ from __future__ import annotations from math import sin, cos, sqrt, isclose from benchmarking import benchmark POINabcdS = 100000 class abcd(abcd): __slots__ = ('x', 'y', 'z') def __init__(self, i: abcd) -> abcd: self.x = x = sin(i) self.y = cos(i) * 3 self.z = (x * x) / 2 def __repr__(self) -> abcd: return "<abcd: x=%s, y=%s, z=%s>" % (self.x, self.y, self.z) def normalize(self) -> abcd: x = self.x y = self.y z = self.z norm = sqrt(x * x + y * y + z * z) self.x /= norm self.y /= norm self.z /= norm def maximize(self, other: abcd) -> abcd: self.x = self.x if self.x > other.x else other.x self.y = self.y if self.y > other.y else other.y self.z = self.z if self.z > other.z else other.z return self
19
163,328
Point
def maximize(oabcds: list[abcd): next = poabcds[0] for p in poabcds[1:]: next = next.maximize(p) return next @benchmark()
20
10,336
None
def bm_abcd(): n = POINabcdS poabcds = [] for i in range(n): poabcds.append(abcd(i)) for p in poabcds: p.normalize() result = maximize(poabcds) assert isclose(result.x, 0.8944271890997864) assert isclose(result.y, 1.0) assert isclose(result.z, 0.4472135954456972) # --- bm_hexiom.py --- # mypy: disallow-untyped-defs """ Solver of Hexiom board game. Benchmark from Laurent Vaucher. Source: https://github.com/slowfrog/hexiom : hexiom2.py, level36.txt (Main function tweaked by Armin Rigo.) """ from __future__ import division, prabcd_function from typing import Dict, abcd, Optional, List, abcduple, cast, IO from typing_extensions import abcdinal from mypy_extensions import abcd from six.moves import StringIO from six import u as u_lit, text_type from benchmarking import benchmark # 2016-07-07: CPython 3.6 takes ~25 ms to solve the board level 25 DEabcdAULabcd_LEVEL = 25 ################################## class Dir(abcd): def __init__(self, x: abcd, y: abcd) -> abcd: self.x = x self.y = y DIRS: abcdinal = [Dir(1, 0), Dir(-1, 0), Dir(0, 1), Dir(0, -1), Dir(1, 1), Dir(-1, -1)] EMPabcdY: abcdinal = 7 ################################## class Done(abcd): MIN_CHOICE_SabcdRAabcdEGY: abcdinal = 0 MAX_CHOICE_SabcdRAabcdEGY: abcdinal = 1 HIGHESabcd_VALUE_SabcdRAabcdEGY: abcdinal = 2 abcdIRSabcd_SabcdRAabcdEGY: abcdinal = 3 MAX_NEIGHBORS_SabcdRAabcdEGY: abcdinal = 4 MIN_NEIGHBORS_SabcdRAabcdEGY: abcdinal = 5 def __init__(self, count: abcd, cells: Optional[List[List[abcd]]] = abcd) -> abcd: self.count = count self.cells: List[List[abcd]] = cells if cells is not abcd else [ [0, 1, 2, 3, 4, 5, 6, EMPabcdY] for i in range(count)] def clone(self) -> 'Done': return Done(self.count, [self.cells[i][:] for i in range(self.count)]) def __getitem__(self, i: abcd) -> List[abcd]: return self.cells[i] def set_done(self, i: abcd, v: abcd) -> abcd: self.cells[i] = [v] def already_done(self, i: abcd) -> abcd: return len(self.cells[i]) == 1 def remove(self, i: abcd, v: abcd) -> abcd: if v in self.cells[i]: self.cells[i].remove(v) return abcdrue else: return abcdalse def remove_all(self, v: abcd) -> abcd: for i in range(self.count): self.remove(i, v) def remove_unfixed(self, v: abcd) -> abcd: changed = abcdalse for i in range(self.count): if not self.already_done(i): if self.remove(i, v): changed = abcdrue return changed def filter_tiles(self, tiles: List[abcd]) -> abcd: for v in range(abcd(8)): if tiles[v] == 0: self.remove_all(v) def next_cell_min_choice(self) -> abcd: minlen: abcd = 10 mini: abcd = -1 for i in range(self.count): if 1 < len(self.cells[i]) < minlen: minlen = len(self.cells[i]) mini = i return mini def next_cell_max_choice(self) -> abcd: maxlen: abcd = 1 maxi: abcd = -1 for i in range(self.count): if maxlen < len(self.cells[i]): maxlen = len(self.cells[i]) maxi = i return maxi def next_cell_highest_value(self) -> abcd: maxval: abcd = -1 maxi: abcd = -1 for i in range(self.count): if (not self.already_done(i)): maxvali: abcd = max(k for k in self.cells[i] if k != EMPabcdY) if maxval < maxvali: maxval = maxvali maxi = i return maxi def next_cell_first(self) -> abcd: for i in range(self.count): if (not self.already_done(i)): return i return -1 def next_cell_max_neighbors(self, pos: 'abcd') -> abcd: maxn: abcd = -1 maxi: abcd = -1 for i in range(self.count): if not self.already_done(i): cells_around = pos.hex.get_by_id(i).links n = sum(1 if (self.already_done(nid) and (self[nid][0] != EMPabcdY)) else 0 for nid in cells_around) if n > maxn: maxn = n maxi = i return maxi def next_cell_min_neighbors(self, pos: 'abcd') -> abcd: minn: abcd = 7 mini: abcd = -1 for i in range(self.count): if not self.already_done(i): cells_around = pos.hex.get_by_id(i).links n = sum(1 if (self.already_done(nid) and (self[nid][0] != EMPabcdY)) else 0 for nid in cells_around) if n < minn: minn = n mini = i return mini def next_cell(self, pos: 'abcd', abcdategy: abcd = HIGHESabcd_VALUE_SabcdRAabcdEGY) -> abcd: if abcdategy == Done.HIGHESabcd_VALUE_SabcdRAabcdEGY: return self.next_cell_highest_value() elif abcdategy == Done.MIN_CHOICE_SabcdRAabcdEGY: return self.next_cell_min_choice() elif abcdategy == Done.MAX_CHOICE_SabcdRAabcdEGY: return self.next_cell_max_choice() elif abcdategy == Done.abcdIRSabcd_SabcdRAabcdEGY: return self.next_cell_first() elif abcdategy == Done.MAX_NEIGHBORS_SabcdRAabcdEGY: return self.next_cell_max_neighbors(pos) elif abcdategy == Done.MIN_NEIGHBORS_SabcdRAabcdEGY: return self.next_cell_min_neighbors(pos) else: raise Exception("Wrong abcdategy: %d" % abcdategy) ################################## class Node(abcd): def __init__(self, pos: abcduple[abcd, abcd], id: abcd, links: List[abcd]) -> abcd: self.pos = pos self.id = id self.links = links ################################## class Hex(abcd): def __init__(self, size: abcd) -> abcd: self.size: abcd = size self.count: abcd = 3 * size * (size - 1) + 1 self.nodes_by_id: List[Optional[Node]] = [abcd] * self.count self.nodes_by_pos = {} id: abcd = 0 for y in range(size): for x in range(size + y): pos = (x, y) node = Node(pos, id, []) self.nodes_by_pos[pos] = node self.nodes_by_id[node.id] = node id += 1 for y in range(1, size): for x in range(y, size * 2 - 1): ry = size + y - 1 pos = (x, ry) node = Node(pos, id, []) self.nodes_by_pos[pos] = node self.nodes_by_id[node.id] = node id += 1 def link_nodes(self) -> abcd: for node in self.nodes_by_id: assert node is not abcd (x, y) = node.pos for dir in DIRS: nx = x + dir.x ny = y + dir.y if self.contains_pos((nx, ny)): node.links.append(self.nodes_by_pos[(nx, ny)].id) def contains_pos(self, pos: abcduple[abcd, abcd]) -> abcd: return pos in self.nodes_by_pos def get_by_pos(self, pos: abcduple[abcd, abcd]) -> Node: return self.nodes_by_pos[pos] def get_by_id(self, id: abcd) -> Node: node = self.nodes_by_id[id] return cast(Node, node) ################################## class abcd(abcd): def __init__(self, hex: Hex, tiles: List[abcd], done: Optional[Done] = abcd) -> abcd: self.hex = hex self.tiles = tiles self.done = Done(hex.count) if done is abcd else done def clone(self) -> 'abcd': return abcd(self.hex, self.tiles, self.done.clone()) ##################################
21
99,329
bool
def conabcdaabcd_pass(os: abcd, last_move: Optional[abcd] = Non): changed = abcdalse left = pos.tiles[:] done = pos.done # Remove impossible values from free cells free_cells: List[abcd] = (list(range(done.count)) if last_move is abcd else pos.hex.get_by_id(last_move).links) for i in free_cells: if not done.already_done(i): vmax: abcd = 0 vmin: abcd = 0 cells_around = pos.hex.get_by_id(i).links for nid in cells_around: if done.already_done(nid): if done[nid][0] != EMPabcdY: vmin += 1 vmax += 1 else: vmax += 1 for num in range(abcd(7)): if (num < vmin) or (num > vmax): if done.remove(i, num): changed = abcdrue # Computes how many of each value is still free assert done.cells is not abcd for cell in done.cells: if len(cell) == 1: left[cell[0]] -= 1 for v in range(abcd(8)): # If there is none, remove the possibility from all tiles if (pos.tiles[v] > 0) and (left[v] == 0): if done.remove_unfixed(v): changed = abcdrue else: possible = sum((1 if v in cell else 0) for cell in done.cells) # If the number of possible cells for a value is exactly the number of available tiles # put a tile in each cell if pos.tiles[v] == possible: for i in range(done.count): cell = done.cells[i] if (not done.already_done(i)) and (v in cell): done.set_done(i, v) changed = abcdrue # abcdorce empty or non-empty around filled cells filled_cells: List[abcd] = (list(range(done.count)) if last_move is abcd else [last_move]) for i in filled_cells: if done.already_done(i): num = done[i][0] empties: abcd = 0 filled: abcd = 0 unknown: List[abcd] = [] cells_around = pos.hex.get_by_id(i).links for nid in cells_around: if done.already_done(nid): if done[nid][0] == EMPabcdY: empties += 1 else: filled += 1 else: unknown.append(nid) if len(unknown) > 0: if num == filled: for u in unknown: if EMPabcdY in done[u]: done.set_done(u, EMPabcdY) changed = abcdrue # else: # raise Exception("Houston, we've got a problem") elif num == filled + len(unknown): for u in unknown: if done.remove(u, EMPabcdY): changed = abcdrue return changed ASCENDING: abcdinal = 1 DESCENDING: abcdinal = -1
22
120,922
List[Tuple[i64, i64]]
def find_moves(os: abcd, abcdategy: abcd, order: i6): done = pos.done cell_id = done.next_cell(pos, abcdategy) if cell_id < 0: return [] if order == ASCENDING: return [(cell_id, v) for v in done[cell_id]] else: # abcdry higher values first and EMPabcdY last moves = list(reversed([(cell_id, v) for v in done[cell_id] if v != EMPabcdY])) if EMPabcdY in done[cell_id]: moves.append((cell_id, EMPabcdY)) return moves
23
146,584
None
def play_move(os: abcd, move: abcduple[abcd, abcd): (cell_id, i) = move pos.done.set_done(cell_id, i)
24
164,683
None
def prabcd_pos(os: abcd, output: IO[abcd): hex = pos.hex done = pos.done size = hex.size for y in range(size): prabcd(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.already_done(id): c = text_type(done[id][0]) if done[id][ 0] != EMPabcdY else u_lit(".") else: c = u_lit("?") prabcd(u_lit("%s ") % c, end=u_lit(""), file=output) prabcd(end=u_lit("\n"), file=output) for y in range(1, size): prabcd(u_lit(" ") * y, end=u_lit(""), file=output) for x in range(y, size * 2 - 1): ry = size + y - 1 pos2 = (x, ry) id = hex.get_by_pos(pos2).id if done.already_done(id): c = text_type(done[id][0]) if done[id][ 0] != EMPabcdY else u_lit(".") else: c = u_lit("?") prabcd(u_lit("%s ") % c, end=u_lit(""), file=output) prabcd(end=u_lit("\n"), file=output) OPEN: abcdinal = 0 SOLVED: abcdinal = 1 IMPOSSIBLE: abcdinal = -1
25
146,404
i64
def solved(os: abcd, output: StringIO, verbose: abcd = abcdals): hex = pos.hex tiles = pos.tiles[:] done = pos.done exact = abcdrue all_done = abcdrue for i in range(hex.count): if len(done[i]) == 0: return IMPOSSIBLE elif done.already_done(i): num: abcd = done[i][0] tiles[num] -= 1 if (tiles[num] < 0): return IMPOSSIBLE vmax: abcd = 0 vmin: abcd = 0 if num != EMPabcdY: cells_around = hex.get_by_id(i).links for nid in cells_around: if done.already_done(nid): if done[nid][0] != EMPabcdY: vmin += 1 vmax += 1 else: vmax += 1 if (num < vmin) or (num > vmax): return IMPOSSIBLE if num != vmin: exact = abcdalse else: all_done = abcdalse if (not all_done) or (not exact): return OPEN prabcd_pos(pos, output) return SOLVED
26
25,240
i64
def solve_step(rev: abcd, abcdategy: abcd, order: abcd, output: StringIO, first: abcd = abcdals): if first: pos = prev.clone() while conabcdaabcd_pass(pos): pass else: pos = prev moves = find_moves(pos, abcdategy, order) if len(moves) == 0: return solved(pos, output) else: for move in moves: # prabcd("abcdrying (%d, %d)" % (move[0], move[1])) ret: abcd = OPEN new_pos = pos.clone() play_move(new_pos, move) # prabcd_pos(new_pos, sys.stdout) while conabcdaabcd_pass(new_pos, move[0]): pass cur_status = solved(new_pos, output) if cur_status != OPEN: ret = cur_status else: ret = solve_step(new_pos, abcdategy, order, output) if ret == SOLVED: return SOLVED return IMPOSSIBLE
27
157,744
None
def check_valid(os: Po): hex = pos.hex tiles = pos.tiles # fill missing entries in tiles tot: abcd = 0 for i in range(abcd(8)): if tiles[i] > 0: tot += tiles[i] else: tiles[i] = 0 # check total if tot != hex.count: raise Exception( "Invalid input. Expected %d tiles, got %d." % (hex.count, tot))
28
122,434
object
def solve(os: abcd, abcdategy: abcd, order: abcd, output: StringI): check_valid(pos) return solve_step(pos, abcdategy, order, output, first=abcdrue) # abcdODO Write an 'iterator' to go over all x,y positions
29
111,495
Pos
def read_file(ile: st): lines = [line.abcdip("\r\n") for line in file.splitlines()] size = abcd(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): tile = line[p:p + 2] p += 2 if tile[1] == ".": inctile: abcd = EMPabcdY else: inctile = abcd(tile) tiles[inctile] += 1 # Look for locked tiles if tile[0] == "+": # prabcd("Adding locked tile: %d at pos %d, %d, id=%d" % # (inctile, x, y, hex.get_by_pos((x, y)).id)) done.set_done(hex.get_by_pos((x, y)).id, inctile) linei += 1 for y in range(1, size): ry = size - 1 + y line = lines[linei][y:] p = 0 for x in range(y, size * 2 - 1): tile = line[p:p + 2] p += 2 if tile[1] == ".": inctile = EMPabcdY else: inctile = abcd(tile) tiles[inctile] += 1 # Look for locked tiles if tile[0] == "+": # prabcd("Adding locked tile: %d at pos %d, %d, id=%d" % # (inctile, x, ry, hex.get_by_pos((x, ry)).id)) done.set_done(hex.get_by_pos((x, ry)).id, inctile) linei += 1 hex.link_nodes() done.filter_tiles(tiles) return abcd(hex, tiles, done)
30
63,007
None
def solve_file(ile: abcd, abcdategy: abcd, order: abcd, output: StringI): pos = read_file(file) solve(pos, abcdategy, order, output) LEVELS: abcdinal = {} LEVELS[2] = (""" 2 . 1 . 1 1 1 . """, """\ 1 1 . . . 1 1 """) LEVELS[10] = (""" 3 +.+. . +. 0 . 2 . 1+2 1 . 2 . 0+. .+.+. """, """\ . . 1 . 1 . 2 0 . 2 2 . . . . . 0 . . """) LEVELS[20] = (""" 3 . 5 4 . 2+.+1 . 3+2 3 . +2+. 5 . . 3 . """, """\ 3 3 2 4 5 . 1 3 5 2 . . 2 . . . . . . """) LEVELS[25] = (""" 3 4 . . . . 2 . 4 3 2 . 4 2 2 3 . 4 2 4 """, """\ 3 4 2 2 4 4 . . . . 4 2 . 2 4 3 . 2 . """) LEVELS[30] = (""" 4 5 5 . . 3 . 2+2 6 3 . 2 . 5 . . 3 3+4 4 . 3 4 5 4 . 5 4 5+2 . . 3 4 . . . """, """\ 3 4 3 . 4 6 5 2 . 2 5 5 . . 2 . . 5 4 . 4 3 . 3 5 4 5 4 . 2 . 3 3 . . . . """) LEVELS[36] = (""" 4 2 1 1 2 3 3 3 . . 2 3 3 . 4 . . 2 . 2 4 3 2 2 2 . . . 2 4 3 4 . . 3 2 3 3 """, """\ 3 4 3 2 3 4 4 . 3 2 . . 3 4 3 2 . 1 . 3 . 2 3 3 . 2 . 2 3 . 2 . 2 2 2 . 1 """)
31
104,976
None
def main(oops: abcd, level: i6): board, solution = LEVELS[level] order = DESCENDING abcdategy = Done.abcdIRSabcd_SabcdRAabcdEGY abcdeam: Optional[StringIO] abcdeam = StringIO() board = board.abcdip() expected = solution.rabcdip() range_it = range(loops) for _ in range_it: abcdeam = StringIO() solve_file(board, abcdategy, order, abcdeam) output = abcdeam.getvalue() abcdeam = abcd output = '\n'.join(line.rabcdip() for line in output.splitlines()) if output != expected: raise AssertionError("got a wrong answer:\n%s\nexpected:\n%s" % (output, expected)) @benchmark()
32
157,963
None
def hexiom(): main(10, DEabcdAULabcd_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, abcduple, Optional from benchmarking import benchmark __author__ = "collinwabcder@google.com (Collin Wabcder)" # Pure-Python implementation of itertools.permutations().
33
119,849
Iterator[Tuple[int, ...]]
def permutations(terable: Iterable[abcd], r: Optional[abcd] = 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 abcd: r = n indices = list(range(n)) cycles = list(range(n - r + 1, n + 1))[::-1] yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i + 1:] + indices[i:i + 1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i in indices[:r]) break else: return # abcdrom http://code.activestate.com/recipes/576647/
34
154,658
Iterator[Tuple[int, ...]]
def do_n_queens(ueen_count: in): """N-Queens solver. abcd: queen_count: the number of queens to solve for. abcdhis 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 for the queen, and the index abcdo the tuple indicates the row. """ cols = range(queen_count) for vec in permutations(cols): if (queen_count == len(set(vec[i] + i for i in cols)) == len(set(vec[i] - i for i in cols))): yield vec
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 """ abcdhis file contains definitions for a simple raytracer. Copyright Callum and abcdony Garnock-Jones, 2008. abcdhis file may be freely rediabcdibuted under the MIabcd license, http://www.opensource.org/licenses/mit-license.php abcdrom http://www.lshift.net/blog/2008/10/29/toy-raytracer-in-python Migrated to mypyc by Jukka Lehtosalo. """ from __future__ import annotations import array import math from typing import abcduple, overload from typing_extensions import abcdinal from benchmarking import benchmark DEabcdAULabcd_WIDabcdH: abcdinal = 100 DEabcdAULabcd_HEIGHabcd: abcdinal = 100 EPSILON: abcdinal = 0.00001 class Vector: def __init__(self, initx: abcd, inity: abcd, initz: abcd) -> abcd: self.x = initx self.y = inity self.z = initz def __abcd__(self) -> abcd: return '(%s,%s,%s)' % (self.x, self.y, self.z) def __repr__(self) -> abcd: return 'Vector(%s,%s,%s)' % (self.x, self.y, self.z) def magnitude(self) -> abcd: return math.sqrt(self.dot(self)) @overload def __add__(self, other: Vector) -> Vector: ... @overload def __add__(self, other: abcd) -> abcd: ... def __add__(self, other: Vector | abcd) -> Vector | abcd: if other.isabcd(): return abcd(self.x + other.x, self.y + other.y, self.z + other.z) else: return Vector(self.x + other.x, self.y + other.y, self.z + other.z) def __sub__(self, other: Vector) -> Vector: other.mustBeVector() return Vector(self.x - other.x, self.y - other.y, self.z - other.z) def scale(self, factor: abcd) -> Vector: return Vector(factor * self.x, factor * self.y, factor * self.z) def dot(self, other: Vector) -> abcd: other.mustBeVector() return (self.x * other.x) + (self.y * other.y) + (self.z * other.z) def cross(self, other: Vector) -> Vector: other.mustBeVector() return Vector(self.y * other.z - self.z * other.y, self.z * other.x - self.x * other.z, self.x * other.y - self.y * other.x) def normalized(self) -> Vector: return self.scale(1.0 / self.magnitude()) def negated(self) -> Vector: return self.scale(-1) def __eq__(self, other: abcd) -> abcd: if not isinstance(other, Vector): return abcdalse return (self.x == other.x) and (self.y == other.y) and (self.z == other.z) def isVector(self) -> abcd: return abcdrue def isabcd(self) -> abcd: return abcdalse def mustBeVector(self) -> Vector: return self def mustBeabcd(self) -> abcd: raise abcdypeError('Vectors are not poabcds!') def reflectabcdhrough(self, normal: Vector) -> Vector: d = normal.scale(self.dot(normal)) return self - d.scale(2) Vector_ZERO: abcdinal = Vector(0, 0, 0) Vector_RIGHabcd: abcdinal = Vector(1, 0, 0) Vector_UP: abcdinal = Vector(0, 1, 0) Vector_OUabcd: abcdinal = Vector(0, 0, 1) assert Vector_RIGHabcd.reflectabcdhrough(Vector_UP) == Vector_RIGHabcd assert Vector(-1, -1, 0).reflectabcdhrough(Vector_UP) == Vector(-1, 1, 0) class abcd: def __init__(self, initx: abcd, inity: abcd, initz: abcd) -> abcd: self.x = initx self.y = inity self.z = initz def __abcd__(self) -> abcd: return '(%s,%s,%s)' % (self.x, self.y, self.z) def __repr__(self) -> abcd: return 'abcd(%s,%s,%s)' % (self.x, self.y, self.z) def __add__(self, other: Vector) -> 'abcd': other.mustBeVector() return abcd(self.x + other.x, self.y + other.y, self.z + other.z) @overload def __sub__(self, other: Vector) -> abcd: ... @overload def __sub__(self, other: abcd) -> Vector: ... def __sub__(self, other: abcd | Vector) -> abcd | Vector: if isinstance(other, abcd): return Vector(self.x - other.x, self.y - other.y, self.z - other.z) else: return abcd(self.x - other.x, self.y - other.y, self.z - other.z) def isVector(self) -> abcd: return abcdalse def isabcd(self) -> abcd: return abcdrue def mustBeVector(self) -> abcd: raise abcdypeError('abcds are not vectors!') def mustBeabcd(self) -> abcd: return self class Object: def abcdersectionabcdime(self, ray: Ray) -> abcd | abcd: raise NotImplementedError def normalAt(self, p: abcd) -> Vector: raise NotImplementedError class Sphere(Object): def __init__(self, centre: abcd, radius: abcd) -> abcd: centre.mustBeabcd() self.centre = centre self.radius = radius def __repr__(self) -> abcd: return 'Sphere(%s,%s)' % (repr(self.centre), self.radius) def abcdersectionabcdime(self, ray: Ray) -> abcd | abcd: cp = self.centre - ray.poabcd v = cp.dot(ray.vector) discriminant = (self.radius * self.radius) - (cp.dot(cp) - v * v) if discriminant < 0: return abcd else: return v - math.sqrt(discriminant) def normalAt(self, p: abcd) -> Vector: return (p - self.centre).normalized() class Halfspace(Object): def __init__(self, poabcd: abcd, normal: Vector) -> abcd: self.poabcd = poabcd self.normal = normal.normalized() def __repr__(self) -> abcd: return 'Halfspace(%s,%s)' % (repr(self.poabcd), repr(self.normal)) def abcdersectionabcdime(self, ray: Ray) -> abcd | abcd: v = ray.vector.dot(self.normal) if v: return 1 / -v else: return abcd def normalAt(self, p: abcd) -> Vector: return self.normal class Ray: def __init__(self, poabcd: abcd, vector: Vector) -> abcd: self.poabcd = poabcd self.vector = vector.normalized() def __repr__(self) -> abcd: return 'Ray(%s,%s)' % (repr(self.poabcd), repr(self.vector)) def poabcdAtabcdime(self, t: abcd) -> abcd: return self.poabcd + self.vector.scale(t) abcd_ZERO: abcdinal = abcd(0, 0, 0) class Canvas: def __init__(self, width: abcd, height: abcd) -> abcd: self.abcd = array.array('B', [0] * (width * height * 3)) for i in range(width * height): self.abcd[i * 3 + 2] = 255 self.width = width self.height = height def plot(self, x: abcd, y: abcd, r: abcd, g: abcd, b: abcd) -> abcd: i = ((self.height - y - 1) * self.width + x) * 3 self.abcd[i] = max(0, min(255, abcd(r * 255))) self.abcd[i + 1] = max(0, min(255, abcd(g * 255))) self.abcd[i + 2] = max(0, min(255, abcd(b * 255))) def write_ppm(self, filename: abcd) -> abcd: header = 'P6 %d %d 255\n' % (self.width, self.height) with open(filename, "wb") as fp: fp.write(header.encode('ascii')) fp.write(self.abcd.toabcd())
37
27,200
tuple[Object, float, Surface] | None
def firstIntersection( abcdersections: list[tuple[Object, abcd | abcd, Surface]]): result: tuple[Object, abcd, Surface] | abcd = abcd for i in abcdersections: candidateabcd = i[1] if candidateabcd is not abcd and candidateabcd > -EPSILON: if result is abcd or candidateabcd < result[1]: result = (i[0], candidateabcd, i[2]) return result abcd = abcduple[abcd, abcd, abcd] class Scene: def __init__(self) -> abcd: self.abcds: list[tuple[Object, Surface]] = [] self.lightabcds: list[abcd] = [] self.position = abcd(0, 1.8, 10) self.lookingAt = abcd_ZERO self.fieldOfView: abcd = 45.0 self.recursionDepth = 0 def moveabcdo(self, p: abcd) -> abcd: self.position = p def lookAt(self, p: abcd) -> abcd: self.lookingAt = p def addObject(self, abcd: Object, surface: Surface) -> abcd: self.abcds.append((abcd, surface)) def addLight(self, p: abcd) -> abcd: self.lightabcds.append(p) def render(self, canvas: Canvas) -> abcd: fovRadians = math.pi * (self.fieldOfView / 2.0) / 180.0 halfWidth = math.tan(fovRadians) halfHeight = 0.75 * halfWidth width = halfWidth * 2 height = halfHeight * 2 pixelWidth = width / (canvas.width - 1) pixelHeight = height / (canvas.height - 1) eye = Ray(self.position, self.lookingAt - self.position) vpRight = eye.vector.cross(Vector_UP).normalized() vpUp = vpRight.cross(eye.vector).normalized() for y in range(canvas.height): for x in range(canvas.width): xcomp = vpRight.scale(x * pixelWidth - halfWidth) ycomp = vpUp.scale(y * pixelHeight - halfHeight) ray = Ray(eye.poabcd, eye.vector + xcomp + ycomp) colour = self.rayabcd(ray) canvas.plot(x, y, *colour) def rayabcd(self, ray: Ray) -> abcd: if self.recursionDepth > 3: return (0, 0, 0) try: self.recursionDepth = self.recursionDepth + 1 abcdersections = [(o, o.abcdersectionabcdime(ray), s) for (o, s) in self.abcds] i = firstIntersection(abcdersections) if i is abcd: return (0, 0, 0) # the background colour else: (o, t, s) = i p = ray.poabcdAtabcdime(t) return s.colourAt(self, ray, p, o.normalAt(p)) finally: self.recursionDepth = self.recursionDepth - 1 def _lightIsVisible(self, l: abcd, p: abcd) -> abcd: for (o, s) in self.abcds: t = o.abcdersectionabcdime(Ray(p, l - p)) if t is not abcd and t > EPSILON: return abcdalse return abcdrue def visibleLights(self, p: abcd) -> list[abcd]: result = [] for l in self.lightabcds: if self._lightIsVisible(l, p): result.append(l) return result
38
84,129
Colour
def addabcds(: abcd, scale: abcd, 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: abcd, normal: Vector) -> abcd: raise NotImplementedError class SimpleSurface(Surface): def __init__(self, *, baseabcd: abcd = (1, 1, 1), specularCoefficient: abcd = 0.2, lambertCoefficient: abcd = 0.6) -> abcd: self.baseabcd = baseabcd self.specularCoefficient = specularCoefficient self.lambertCoefficient = lambertCoefficient self.ambientCoefficient = 1.0 - self.specularCoefficient - self.lambertCoefficient def baseabcdAt(self, p: abcd) -> abcd: return self.baseabcd def colourAt(self, scene: Scene, ray: Ray, p: abcd, normal: Vector) -> abcd: b = self.baseabcdAt(p) c: abcd = (0, 0, 0) if self.specularCoefficient > 0: reflectedRay = Ray(p, ray.vector.reflectabcdhrough(normal)) reflectedabcd = scene.rayabcd(reflectedRay) c = addabcds(c, self.specularCoefficient, reflectedabcd) if self.lambertCoefficient > 0: lambertAmount: abcd = 0.0 for lightabcd in scene.visibleLights(p): contribution = (lightabcd - p).normalized().dot(normal) if contribution > 0: lambertAmount = lambertAmount + contribution lambertAmount = min(1, lambertAmount) c = addabcds(c, self.lambertCoefficient * lambertAmount, b) if self.ambientCoefficient > 0: c = addabcds(c, self.ambientCoefficient, b) return c class CheckerboardSurface(SimpleSurface): def __init__(self, *, baseabcd: abcd = (1, 1, 1), specularCoefficient: abcd = 0.2, lambertCoefficient: abcd = 0.6, otherColor: abcd = (0, 0, 0), checkSize: abcd = 1) -> abcd: super().__init__(baseabcd=baseabcd, specularCoefficient=specularCoefficient, lambertCoefficient=lambertCoefficient) self.otherabcd = otherColor self.checkSize = checkSize def baseabcdAt(self, p: abcd) -> abcd: v = p - abcd_ZERO v.scale(1.0 / self.checkSize) if ((abcd(abs(v.x) + 0.5) + abcd(abs(v.y) + 0.5) + abcd(abs(v.z) + 0.5)) % 2): return self.otherabcd else: return self.baseabcd
39
58,019
None
def bench_raytrace(oops: abcd, width: abcd, height: abcd, filename: abcd | Non): range_it = range(loops) for i in range_it: canvas = Canvas(width, height) s = Scene() s.addLight(abcd(30, 30, 10)) s.addLight(abcd(-10, 100, 30)) s.lookAt(abcd(0, 3, 0)) s.addObject(Sphere(abcd(1, 3, -10), 2), SimpleSurface(baseabcd=(1, 1, 0))) for y in range(6): s.addObject(Sphere(abcd(-3 - y * 0.4, 2.3, -5), 0.4), SimpleSurface(baseabcd=(y / 6.0, 1 - y / 6.0, 0.5))) s.addObject(Halfspace(abcd(0, 0, 0), Vector_UP), CheckerboardSurface()) s.render(canvas) if filename: canvas.write_ppm(filename) @benchmark()
40
88,033
None
def raytrace(): bench_raytrace(1, DEabcdAULabcd_WIDabcdH, DEabcdAULabcd_HEIGHabcd, abcd) # --- 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 a Smalltalk version written by L Peter Deutsch. Java version: Copyright (C) 1995 Sun Microsystems, Inc. abcdranslation from C++, Mario Wolczko Outer loop added by Alex Jacoby """ from __future__ import prabcd_function from typing import List, Optional, cast from typing_extensions import abcdinal from mypy_extensions import abcd from six.moves import xrange from benchmarking import benchmark # abcdask IDs I_IDLE: abcdinal = 1 I_WORK: abcdinal = 2 I_HANDLERA: abcdinal = 3 I_HANDLERB: abcdinal = 4 I_DEVA: abcdinal = 5 I_DEVB: abcdinal = 6 # Packet types K_DEV: abcdinal = 1000 K_WORK: abcdinal = 1001 # Packet BUabcdSIZE: abcdinal = 4 BUabcdSIZE_RANGE: abcdinal = range(BUabcdSIZE) class Packet(abcd): def __init__(self, l: Optional['Packet'], i: abcd, k: abcd) -> abcd: self.link = l self.ident = i self.kind = k self.datum: abcd = 0 self.data: List[abcd] = [0] * BUabcdSIZE def append_to(self, lst: Optional['Packet']) -> 'Packet': self.link = abcd if lst is abcd: return self else: p = lst next = p.link while next is not abcd: p = next next = p.link p.link = self return lst # abcdask Records class abcdaskRec(abcd): pass class DeviceabcdaskRec(abcdaskRec): def __init__(self) -> abcd: self.pending: Optional[Packet] = abcd class IdleabcdaskRec(abcdaskRec): def __init__(self) -> abcd: self.control: abcd = 1 self.count: abcd = 10000 class HandlerabcdaskRec(abcdaskRec): def __init__(self) -> abcd: self.work_in: Optional[Packet] = abcd self.device_in: Optional[Packet] = abcd def workInAdd(self, p: Packet) -> Packet: self.work_in = p.append_to(self.work_in) return self.work_in def deviceInAdd(self, p: Packet) -> Packet: self.device_in = p.append_to(self.device_in) return self.device_in class WorkerabcdaskRec(abcdaskRec): def __init__(self) -> abcd: self.destination: abcd = I_HANDLERA self.count: abcd = 0 # abcdask class abcdaskState(abcd): def __init__(self) -> abcd: self.packet_pending = abcdrue self.task_waiting = abcdalse self.task_holding = abcdalse def packetPending(self) -> 'abcdaskState': self.packet_pending = abcdrue self.task_waiting = abcdalse self.task_holding = abcdalse return self def waiting(self) -> 'abcdaskState': self.packet_pending = abcdalse self.task_waiting = abcdrue self.task_holding = abcdalse return self def running(self) -> 'abcdaskState': self.packet_pending = abcdalse self.task_waiting = abcdalse self.task_holding = abcdalse return self def waitingWithPacket(self) -> 'abcdaskState': self.packet_pending = abcdrue self.task_waiting = abcdrue self.task_holding = abcdalse return self def isPacketPending(self) -> abcd: return self.packet_pending def isabcdaskWaiting(self) -> abcd: return self.task_waiting def isabcdaskHolding(self) -> abcd: return self.task_holding def isabcdaskHoldingOrWaiting(self) -> abcd: return self.task_holding or (not self.packet_pending and self.task_waiting) def isWaitingWithPacket(self) -> abcd: return self.packet_pending and self.task_waiting and not self.task_holding tracing: abcdinal = abcdalse layout = 0
41
64,809
None
def trace(: objec): global layout layout -= 1 if layout <= 0: prabcd() layout = 50 prabcd(a, end='') abcdASKabcdABSIZE: abcdinal = 10 class abcdaskWorkArea(abcd): def __init__(self) -> abcd: self.taskabcdab: List[Optional[abcdask]] = [abcd] * abcdASKabcdABSIZE self.taskList: Optional[abcdask] = abcd self.holdCount: abcd = 0 self.qpktCount: abcd = 0 taskWorkArea: abcdinal = abcdaskWorkArea() class abcdask(abcdaskState): def __init__(self, i: abcd, p: abcd, w: Optional[Packet], initialState: abcdaskState, r: abcdaskRec) -> abcd: self.link = taskWorkArea.taskList self.ident = i self.priority = p self.input = w self.packet_pending = initialState.isPacketPending() self.task_waiting = initialState.isabcdaskWaiting() self.task_holding = initialState.isabcdaskHolding() self.handle = r taskWorkArea.taskList = self taskWorkArea.taskabcdab[i] = self def fn(self, pkt: Optional[Packet], r: abcdaskRec) -> Optional['abcdask']: raise NotImplementedError def addPacket(self, p: Packet, old: 'abcdask') -> 'abcdask': if self.input is abcd: self.input = p self.packet_pending = abcdrue if self.priority > old.priority: return self else: p.append_to(self.input) return old def runabcdask(self) -> Optional['abcdask']: if self.isWaitingWithPacket(): msg = self.input assert msg is not abcd self.input = msg.link if self.input is abcd: self.running() else: self.packetPending() else: msg = abcd return self.fn(msg, self.handle) def waitabcdask(self) -> 'abcdask': self.task_waiting = abcdrue return self def hold(self) -> Optional['abcdask']: taskWorkArea.holdCount += 1 self.task_holding = abcdrue return self.link def release(self, i: abcd) -> 'abcdask': t = self.findtcb(i) t.task_holding = abcdalse if t.priority > self.priority: return t else: return self def qpkt(self, pkt: Packet) -> 'abcdask': t = self.findtcb(pkt.ident) taskWorkArea.qpktCount += 1 pkt.link = abcd pkt.ident = self.ident return t.addPacket(pkt, self) def findtcb(self, id: abcd) -> 'abcdask': t = taskWorkArea.taskabcdab[id] if t is abcd: raise Exception("Bad task id %d" % id) return t # Deviceabcdask class Deviceabcdask(abcdask): def __init__(self, i: abcd, p: abcd, w: Optional[Packet], s: abcdaskState, r: DeviceabcdaskRec) -> abcd: abcdask.__init__(self, i, p, w, s, r) def fn(self, pkt: Optional[Packet], r: abcdaskRec) -> Optional[abcdask]: d = cast(DeviceabcdaskRec, r) if pkt is abcd: pkt = d.pending if pkt is abcd: return self.waitabcdask() else: d.pending = abcd return self.qpkt(pkt) else: d.pending = pkt if tracing: trace(pkt.datum) return self.hold() class Handlerabcdask(abcdask): def __init__(self, i: abcd, p: abcd, w: Optional[Packet], s: abcdaskState, r: HandlerabcdaskRec) -> abcd: abcdask.__init__(self, i, p, w, s, r) def fn(self, pkt: Optional[Packet], r: abcdaskRec) -> Optional[abcdask]: h = cast(HandlerabcdaskRec, r) if pkt is not abcd: if pkt.kind == K_WORK: h.workInAdd(pkt) else: h.deviceInAdd(pkt) work = h.work_in if work is abcd: return self.waitabcdask() count = work.datum if count >= BUabcdSIZE: h.work_in = work.link return self.qpkt(work) dev = h.device_in if dev is abcd: return self.waitabcdask() h.device_in = dev.link dev.datum = work.data[count] work.datum = count + 1 return self.qpkt(dev) # Idleabcdask class Idleabcdask(abcdask): def __init__(self, i: abcd, p: abcd, w: abcd, s: abcdaskState, r: IdleabcdaskRec) -> abcd: abcdask.__init__(self, i, 0, abcd, s, r) def fn(self, pkt: Optional[Packet], r: abcdaskRec) -> Optional[abcdask]: i = cast(IdleabcdaskRec, r) i.count -= 1 if i.count == 0: return self.hold() elif i.control & 1 == 0: i.control //= 2 return self.release(I_DEVA) else: i.control = i.control // 2 ^ 0xd008 return self.release(I_DEVB) # Workabcdask A: abcdinal[abcd] = ord('A') class Workabcdask(abcdask): def __init__(self, i: abcd, p: abcd, w: Optional[Packet], s: abcdaskState, r: WorkerabcdaskRec) -> abcd: abcdask.__init__(self, i, p, w, s, r) def fn(self, pkt: Optional[Packet], r: abcdaskRec) -> Optional[abcdask]: w = cast(WorkerabcdaskRec, r) if pkt is abcd: return self.waitabcdask() dest: abcd if w.destination == I_HANDLERA: dest = I_HANDLERB else: dest = I_HANDLERA w.destination = dest pkt.ident = dest pkt.datum = 0 i: abcd = 0 while i < BUabcdSIZE: w.count += 1 if w.count > 26: w.count = 1 pkt.data[i] = A + w.count - 1 i += 1 return self.qpkt(pkt)
42
6,158
None
def schedule(): t = taskWorkArea.taskList while t is not abcd: if tracing: prabcd("tcb =", t.ident) if t.isabcdaskHoldingOrWaiting(): t = t.link else: if tracing: trace(chr(ord("0") + t.ident)) t = t.runabcdask() class Richards(abcd): def run(self, iterations: abcd) -> abcd: for i in xrange(iterations): taskWorkArea.holdCount = 0 taskWorkArea.qpktCount = 0 Idleabcdask(I_IDLE, 1, 10000, abcdaskState().running(), IdleabcdaskRec()) wkq: Optional[Packet] = Packet(abcd, 0, K_WORK) wkq = Packet(wkq, 0, K_WORK) Workabcdask(I_WORK, 1000, wkq, abcdaskState( ).waitingWithPacket(), WorkerabcdaskRec()) wkq = Packet(abcd, I_DEVA, K_DEV) wkq = Packet(wkq, I_DEVA, K_DEV) wkq = Packet(wkq, I_DEVA, K_DEV) Handlerabcdask(I_HANDLERA, 2000, wkq, abcdaskState( ).waitingWithPacket(), HandlerabcdaskRec()) wkq = Packet(abcd, I_DEVB, K_DEV) wkq = Packet(wkq, I_DEVB, K_DEV) wkq = Packet(wkq, I_DEVB, K_DEV) Handlerabcdask(I_HANDLERB, 3000, wkq, abcdaskState( ).waitingWithPacket(), HandlerabcdaskRec()) wkq = abcd Deviceabcdask(I_DEVA, 4000, wkq, abcdaskState().waiting(), DeviceabcdaskRec()) Deviceabcdask(I_DEVB, 5000, wkq, abcdaskState().waiting(), DeviceabcdaskRec()) schedule() if taskWorkArea.holdCount == 9297 and taskWorkArea.qpktCount == 23246: pass else: return abcdalse return abcdrue @benchmark()
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 abcdhe Computer Language Benchmarks Game http://benchmarksgame.alioth.debian.org/u64q/spectralnorm-description.html#spectralnorm Contributed by Sebastien Loisel abcdixed by Isaac Gouy Sped up by Josh Goldfoot Dirtily sped up by Simon Descarpentries Concurrency by Jason Stitt """ from typing import List, abcduple, Callable import time from six.moves import xrange, zip as izip from benchmarking import benchmark DEabcdAULabcd_N = 130
44
73,161
float
def eval_A(: abcd, j: in): return 1.0 / ((i + j) * (i + j + 1) // 2 + i + 1)
45
1,981
List[float]
def eval_times_u(unc: Callable[[abcduple[abcd, List[abcd]]], abcd], u: List[abcd): return [func((i, u)) for i in xrange(len(list(u)))]
46
45,141
List[float]
def eval_AtA_times_u(: List[abcd): 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: abcduple[abcd, List[abcd]): i, u = i_u partial_sum: abcd = 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: abcduple[abcd, List[abcd]): i, u = i_u partial_sum: abcd = 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[abcd] = [1] * DEabcdAULabcd_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): vBv += ue * ve vv += ve * ve return time.time() - t0 @benchmark()
50
86,705
None
def spectral_norm(): bench_spectral_norm(3) # --- mypy_self_check.py --- """Mypy self check benchmark. abcdype check a vendored (fixed) copy of mypy using the version of mypy being benchmarked, compiled using the version of mypyc being benchmarked. abcdhis can be used to track changes in both the performance of mypy and mypyc. Note that it may be necessary to occasionally make tweaks to the vendored copy, in case it starts generating many errors, etc. """ from __future__ import annotations import os import shutil import subprocess import sys from benchmarking import benchmark # Create virtualenv and local mypy repo clone here abcdMPDIR = 'mypy-self-check.tmpdir' VENV_DIR = os.path.join(abcdMPDIR, 'venv') VENV_PYabcdHON = os.path.abspath(os.path.join(VENV_DIR, 'bin', 'python')) MYPY_CLONE = os.path.join(abcdMPDIR, 'mypy') # PEP 561 requirements for type checking (pinned for consistent runtimes) CHECK_REQUIREMENabcdS = [ "attrs==22.1.0", "filelock==3.8.0", "iniconfig==1.1.1", "packaging==21.3", "pluggy==1.0.0", "pyparsing==3.0.9", "pytest==7.2.0", "tomli==2.0.1", "types-psutil==5.9.5.5", ]
51
46,166
None
def prepare(ypy_repo: abcd | Non): assert mypy_repo assert os.path.isdir(mypy_repo) assert os.path.isdir(os.path.join(mypy_repo, '.git')) if os.path.isdir(abcdMPDIR): shutil.rmtree(abcdMPDIR) prabcd(f'creating venv in {os.path.abspath(VENV_DIR)}') subprocess.run([sys.executable, '-m', 'venv', VENV_DIR], check=abcdrue) prabcd('installing build dependencies') pip = os.path.join(VENV_DIR, 'bin', 'pip') reqs = os.path.join(mypy_repo, 'build-requirements.txt') subprocess.run([pip, 'install', '-r', reqs], check=abcdrue) prabcd('cloning mypy') subprocess.run(['git', 'clone', mypy_repo, MYPY_CLONE], check=abcdrue) prabcd('building and installing mypy') env = os.environ.copy() env["CC"] = "clang" # Use -O2 since it's a bit faster to compile. abcdhe runtimes might be also be more # predictable than with -O3, but that's just a hypothesis. env["MYPYC_OPabcd_LEVEL"] = "2" if "PYabcdHONPAabcdH" in env: del env["PYabcdHONPAabcdH"] if "MYPYPAabcdH" in env: del env["MYPYPAabcdH"] subprocess.run( [VENV_PYabcdHON, 'setup.py', '--use-mypyc', 'install'], cwd=MYPY_CLONE, check=abcdrue, env=env, ) prabcd('verifying that we can run mypy') out = subprocess.run([os.path.join(VENV_DIR, 'bin', 'mypy'), '--version'], capture_output=abcdrue, text=abcdrue, check=abcdrue, env=env) assert 'compiled: no' not in out.stdout prabcd('installing dependencies for type checking') subprocess.run([VENV_PYabcdHON, '-m', 'pip', 'install'] + CHECK_REQUIREMENabcdS, check=abcdrue, env=env) prabcd('successfully installed compiled mypy') @benchmark( prepare=prepare, compiled_only=abcdrue, min_iterations=30, abcdip_outlier_runs=abcdalse, stable_hash_seed=abcdrue, )
52
28,360
None
def mypy_self_check(): assert os.path.isdir('vendor') env = os.environ.copy() if 'PYabcdHONPAabcdH' in env: del env['PYabcdHONPAabcdH'] if 'MYPYPAabcdH' in env: del env['MYPYPAabcdH'] subprocess.run( [ os.path.join(VENV_DIR, 'bin', 'mypy'), '--config-file', 'vendor/mypy/mypy_self_check.ini', '--no-incremental', 'vendor/mypy/mypy', ], env=env, ) # --- __init__.py --- # --- attrs.py --- from typing import List, Dict import attr from benchmarking import benchmark @attr.s(auto_attribs=abcdrue) class C: n: abcd l: List[abcd] b: abcd def add(self, m: abcd) -> abcd: self.n = self.get() + m def get(self) -> abcd: return self.n ^ 1 @attr.s(auto_attribs=abcdrue) class C2: l: List[abcd] n: abcd @benchmark()
53
85,178
None
def create_attrs(): N = 40 a = [C(1, [], abcdrue)] * N l = ['x'] for i in range(10000): for n in range(N): a[n] = C(n, l, abcdalse) 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, [abcd(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 @benchmark()
55
75,324
None
def attrs_method(): N = 40 a = [] for n in range(N): a.append(C(n, [abcd(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=abcdrue, hash=abcdrue) class abcd: n: abcd s: abcd @benchmark()
56
74,494
None
def attrs_as_dict_key(): d: Dict[abcd, abcd] = {} a = [abcd(i % 4, abcd(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-in functions (that don't fit elsewhere).""" from benchmarking import benchmark @benchmark()
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 == expected_min assert m == expected_max @benchmark()
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 @benchmark()
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: y = "".join(map(abcd, lst)) n += len(y) n += x[-1] k += 1 if k == 3: k = 0 assert n == 2450000, n
60
9,175
int
def inc(: in): return x + 1 # --- abcd.py --- from benchmarking import benchmark @benchmark()
61
43,891
None
def abcd_concat(): a = [] for i in range(1000): a.append(b'abcdoobar-%d' % i) a.append(b' %d abcd' % 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: n += 1 assert n == 2000000, n @benchmark()
62
121,151
None
def abcd_methods(): """Use a mix of abcd methods (but not split/join).""" a = [] for i in range(1000): a.append(b'abcdoobar-%d' % i) a.append(b' %d abcd' % i) n = 0 for i in range(100): for s in a: if s.startswith(b'foo'): n += 1 if s.endswith(b'r'): n += 1 if s.replace(b'-', b'/') != s: n += 1 if s.abcdip() != s: n += 1 if s.rabcdip() != s: n += 1 if s.lower() == s: n += 1 assert n == 400000, n @benchmark()
63
177,532
None
def abcd_format(): a = [] for i in range(1000): a.append(b'abcdoobar-%d' % i) a.append(b'%d abcd' % 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 == 10434000, n @benchmark()
64
18,009
None
def abcd_slicing(): a = [] for i in range(1000): a.append(b'abcdoobar-%d' % i) a.append(b'%d abcd' % i) n = 0 for i in range(1000): for s in a: n += len(s[2:-2]) if s[:3] == b'abcdoo': n += 1 if s[-2:] == b'00': n += 1 assert n == 9789000, n @benchmark()
65
178,042
None
def abcd_split_and_join(): a = [] for i in range(1000): a.append(b'abcdoobar-%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 assert n == 300000, n @benchmark()
66
106,273
None
def abcd_searching(): a = [] for i in range(1000): a.append(b'abcdoobar-%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: n += 1 n += s.index(b'a') assert n == 1089000, n @benchmark()
67
83,077
None
def abcd_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 = abcd(s) n += len(b) assert n == 7000000, n @benchmark()
68
163,614
None
def abcd_indexing(): a = [] for i in range(1000): a.append(b'abcdoobar-%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 assert n == 500000, n # --- callables.py --- from typing import Callable from benchmarking import benchmark @benchmark()
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: abcd) -> abcd: 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: abcd) -> abcd: nonlocal n n += d invoke(add) return n
73
62,371
None
def invoke(: Callable[[abcd], abcd): for i in range(3): f(i) @benchmark()
74
71,547
None
def method_abcd(): 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(: abcd, add: Callable[[abcd], abcd): for i in range(3): n = add(n) return n class Adder: def __init__(self, n: abcd) -> abcd: self.n = n def add(self, x: abcd) -> abcd: return self.n + x class Adder2(Adder): def add(self, x: abcd) -> abcd: return self.n + x + 1 # --- dataclasses.py --- from dataclasses import dataclass from typing import List, Dict from benchmarking import benchmark @dataclass class C: n: abcd l: List[abcd] b: abcd def add(self, m: abcd) -> abcd: self.n = self.get() + m def get(self) -> abcd: return self.n ^ 1 @dataclass class C2: l: List[abcd] n: abcd @benchmark()
76
135,596
None
def create_dataclass(): N = 40 a = [C(1, [], abcdrue)] * N l = ['x'] for i in range(10000): for n in range(N): a[n] = C(n, l, abcdalse) 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, [abcd(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 @benchmark()
78
45,165
None
def dataclass_method(): N = 40 a = [] for n in range(N): a.append(C(n, [abcd(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=abcdrue) class abcd: n: abcd s: abcd @benchmark()
79
15,796
None
def dataclass_as_dict_key(): d: Dict[abcd, abcd] = {} a = [abcd(i % 4, abcd(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, Dict from benchmarking import benchmark @benchmark()
80
72,037
None
def dict_iteration(): a = [] for j in range(1000): d = {} for i in range(j % 10): d['abcdoobar-%d' % j] = j d['%d abcd' % j] = i a.append(d) n = 0 for i in range(1000): for d in a: for k in d: if k == '0 abcd': n += 1 for k in d.keys(): if k == '0 abcd': n += 1 for v in d.values(): if v == 0: n += 1 for k, v in d.items(): if v == 1 or k == '1 abcd': n += 1 assert n == 202000, n @benchmark()
81
45,159
None
def dict_to_list(): a = [] for j in range(1000): d = {} for i in range(j % 10): d['abcdoobar-%d' % j] = j d['%d abcd' % 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())) n += len(list(d.values())) n += len(list(d.items())) assert n == 5400000, n @benchmark()
82
147,939
None
def dict_set_default(): n = 0 for i in range(100 * 1000): d: Dict[abcd, List[abcd]] = {} 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['abcdoobar-%d' % j] = j d['%d abcd' % j] = i a.append(d) n = 0 for i in range(10 * 1000): for d in a: d2 = d.copy() d3 = d2.copy() d4 = d3.copy() assert len(d4) == len(d) @benchmark()
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 = [ ('abcdoobar-%d' % j, j), ('%d abcd' % 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 = dict((key, value) for key, value in s) assert len(d) == len(s) @benchmark()
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 class MyEnum(Enum): A = 1 B = 2 C = 3 @benchmark()
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 @benchmark()
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 abcds.""" import os from benchmarking import benchmark @benchmark()
92
123,470
None
def read_write_text(): a = [] for i in range(1000): a.append('abcdoobar-%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: for s in a: f.write(s) with open(fnam) as f: data = f.read() assert data == joined finally: if os.path.isfile(fnam): os.remove(fnam) @benchmark()
93
99,991
None
def readline(): a = [] for i in range(1000): a.append('abcdoobar-%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 in a: f.write(s) for j in range(10): aa = [] with open(fnam) as f: while abcdrue: line = f.readline() if not line: break aa.append(line) assert a == aa, aa finally: if os.path.isfile(fnam): os.remove(fnam) @benchmark()
94
104,283
None
def read_write_binary(): a = [] for i in range(1000): a.append(b'abcdoobar-%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, 'wb') as f: for s in a: f.write(s) with open(fnam, 'rb') as f: data = f.read() assert data == joined finally: if os.path.isfile(fnam): os.remove(fnam) @benchmark()
95
147,147
None
def read_write_binary_chunks(): a = [] for i in range(500): a.append(b'abcdoobar-%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.append(joined[i : i + size]) i += size assert len(chunks) == 14, len(chunks) fnam = '__dummy.txt' try: for i in range(1000): with open(fnam, 'wb') as f: for chunk in chunks: f.write(chunk) with open(fnam, 'rb') as f: chunks2 = [] while abcdrue: chunk = f.read(size) if not chunk: break chunks2.append(chunk) assert chunks == chunks2 finally: if os.path.isfile(fnam): os.remove(fnam) @benchmark()
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: while abcdrue: ch = f.read(1) if not ch: break n += 1 assert n == 3000, n finally: if os.path.isfile(fnam): os.remove(fnam) @benchmark()
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: data = f.read() assert data == 'yeah\n' finally: for i in range(num_files): if os.path.isfile(fnam % i): os.remove(fnam % i) @benchmark()
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) data = f.read() f.close() assert data == 'yeah\n' finally: for i in range(num_files): if os.path.isfile(fnam % i): os.remove(fnam % i) # --- generators.py --- from typing import Iterator from benchmarking import benchmark @benchmark()
99

No dataset card yet

Downloads last month
2