python set查找的时间复杂度_python - 如何从hashset中添加和检索字符串的时间复杂度_hash_酷徒编程知识库...

一个快速而不科学的基准:import time

def make_string(c, n):

return c * n

def make_tuple(el, n):

return (el,) * n

def hashtest(gen, n):

# First compute how long generation alone takes

gen_time = time.perf_counter()

for x in range(n):

gen()

gen_time = time.perf_counter() - gen_time

# Then compute how long hashing and generation takes

hash_and_gen_time = time.perf_counter()

for x in range(n):

hash(gen())

hash_and_gen_time = time.perf_counter() - hash_and_gen_time

# Return the two

return (hash_and_gen_time, gen_time)

for gen in (make_string, make_tuple):

for obj_length in (10000, 20000, 40000):

t = f"{gen.__name__} x {obj_length}"

# Using `b'hello'.decode()` here to avoid any cached hash shenanigans

hash_and_gen_time, gen_time = hashtest(

lambda: gen(b"hello".decode(), obj_length), 10000

)

hash_time = hash_and_gen_time - gen_time

print(t, hash_time, obj_length / hash_time)

输出make_string x 10000 0.23490356100000004 42570.66158311665

make_string x 20000 0.47143921999999994 42423.284172241765

make_string x 40000 0.942087403 42458.905482254915

make_tuple x 10000 0.45578034300000025 21940.393335480014

make_tuple x 20000 0.9328520900000008 21439.62608263008

make_tuple x 40000 1.8562772150000004 21548.505620158674

基本上说哈希序列是字符串或元组,是线性时间,但是哈希字符串比散列组快得多。

import time

s = ('x' * 500_000_000)

t0 = time.perf_counter()

a = hash(s)

t1 = time.perf_counter()

print(t1 - t0)

t0 = time.perf_counter()

b = hash(s)

t2 = time.perf_counter()

assert a == b

print(t2 - t0)

输出0.26157095399999997

1.201999999977943e-06

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值