defdo_the_thing(required_arg, optional_arg=1, other_optional_arg=False): """ I am a docstring """ print((required_arg, type(required_arg))) print((optional_arg, type(optional_arg))) print((other_optional_arg, type(other_optional_arg)))
@argh.arg('--bool-arg-for-flag', '-b', help="Flip this flag for things") @argh.arg('arg_with_choices', choices=['one', 'two', 'three']) defdo_the_other_thing(arg_with_choices, bool_arg_for_flag=False): print(arg_with_choices) print(bool_arg_for_flag)
if __name__ == '__main__': # argh.dispatch_command(do_the_thing) argh.dispatch_commands([do_the_thing, do_the_other_thing])
defmsgpack_example_1(): example_dict = {i: random.random() for i in range(10000)}
with open('json_file.json', 'w') as f: json.dump(example_dict, f) with open('json_file.json') as f: back_from_json = json.load(f)
# Saving and loading with open('msgpack_file.msgpack', 'wb') as f: # f.write(msgpack.packb(example_dict)) # f.write(msgpack.packb(example_dict, use_single_float=True)) f.write(msgpack.packb(example_dict))
with open('msgpack_file.msgpack', 'rb') as f: back_from_msgpack = msgpack.unpackb(f.read())
# Data integrity print(type(next(iter(back_from_json.keys())))) print(type(next(iter(back_from_msgpack.keys()))))
defmsgpack_example_2(): list_of_dicts = [{0: random.random()} for i in range(100)] with open('streamed.msgpack', 'wb') as f: for d in list_of_dicts: f.write(msgpack.packb(d))
# 迭代读取 with open('streamed.msgpack', 'rb') as f: loaded_list_of_dicts = [item for item in msgpack.Unpacker(f)]
# start = time.time() # with ThreadPoolExecutor(4) as ex: # ex.map(jitted_func, range(1000)) # end = time.time() # print("[Python origin test] Used time: ", end - start)
start = time.time() with ThreadPoolExecutor(4) as ex: ex.map(jitted_func_2, range(100)) end = time.time() print("[Numpy origin test] Used time: ", end - start)
start = time.time() with ThreadPoolExecutor(4) as ex: ex.map(jitted_func_3, range(100)) end = time.time() print("[Numpy no gil test] Used time: ", end - start)
for ii in range(len(times)): if ii == 0: continue t = times[ii] a = friction_fn(v, vt) - 100*x v = v + a*dt x = x + v*dt positions[ii] = x/x0 return times, positions
for ii in range(len(times)): if ii == 0: continue t = times[ii] a = friction_fn(v, vt) - 100*x v = v + a*dt x = x + v*dt positions[ii] = x/x0 return times, positions
_ = simulate_spring_mass_funky_damper(0.1)
运行时间 1.99 ms,加速 200x。
再加速:
1 2 3 4 5
# 使用多线程 from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(8) as ex: ex.map(simulate_spring_mass_funky_damper, np.arange(0, 1000, 0.1))
for ii in range(len(times)): if ii == 0: continue t = times[ii] a = friction_fn(v, vt) - 100*x v = v + a*dt x = x + v*dt positions[ii] = x/x0 return times, positions