模拟计算hash前面N个0需要的时间
写了一个python代码用来模拟计算当hash前面有N个0时需要多长时间。
代码如下:
import hashlib import time from datetime import timedelta from plyer import notification def find_hash_with_prefix_zeros(prefix_length=6): # 初始字符串 base_text = "Hello, World!" # 计数器 counter = 0 while True: # 构建新的字符串 text = f"{base_text}{counter}" # 计算哈希值 hash_value = hashlib.sha256(text.encode()).hexdigest() # print(f"hash_value:{hash_value}") # 检查哈希值前缀是否包含指定数量的0 if hash_value.startswith('0' * prefix_length): notification.notify( title="通知", message="hash计算完成", app_name="hash计算", timeout=10 # 通知显示的时间,单位为秒 ) print(f"Found after {counter} attempts:") print(f"Text: {text}") print(f"Hash: {hash_value} prefix_length={prefix_length}") break # 增加计数器 counter += 1 # print(f"counter:{counter}") # 计算某个函数需要运行多长时间 def measure_runtime(func, *args, **kwargs): # 记录开始时间 start_time = time.time() # 调用函数 func(*args, **kwargs) # 记录结束时间 end_time = time.time() # 计算运行时间(秒) runtime_seconds = end_time - start_time # 将运行时间转换为 timedelta 对象 runtime = timedelta(seconds=runtime_seconds) # 打印运行时间,格式为小时:分钟:秒 print(f"函数运行时间: {runtime}") def main(): # 调用函数,寻找前缀包含N个0的哈希值 measure_runtime(find_hash_with_prefix_zeros, prefix_length=6) if __name__ == '__main__': main()
计算过程打印日志如下:
hash前面N个0的时间记录:
9个0就需要4天时间了:
我们可以大概预估下:
后面的就不跑了,btc目前前导19个0,可想而知像btc的挖矿难度了。
随着0的数量的增加,计算的时长就越长:
我电脑的配置:AMD Ryzen 7 8845HS w/ Radeon 780M Graphics 3.80 GHz
这篇分享文章就到这里啦!如果你对文章内容有疑问或想要深入讨论,欢迎在评论区留言,我会尽力回答。同时,如果你觉得这篇文章对你有帮助,不妨点个赞并分享给其他同学,让更多人受益。
想要了解更多相关知识,可以查看我以往的文章,其中有许多精彩内容。记得关注我,获取及时更新,我们可以一起学习、讨论技术,共同进步。
感谢你的阅读与支持,期待在未来的文章中与你再次相遇!
我的微信公众号:【xdub】,欢迎大家订阅,我会同步文章到公众号上。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律