zoukankan      html  css  js  c++  java
  • 【python】迭代器与嵌套for循环生成密码字典速度对比

    前言

    分别使用迭代器嵌套for循环生成包含所有由数字组成的长度为8的密码字典,也就是从0000000099999999

    代码

    • 迭代器
    import time
    t1 = time.time()
    import itertools as its
    iterator = its.product('0123456789', repeat=8)
    f = open('pwd.txt', 'w')
    for i in iterator:
        f.write(''.join(i)+'
    ')
    f.close()
    t2 = time.time()
    print(t2-t1)
    # 62.58520317077637
    
    • 嵌套for循环
    import time
    t1 = time.time()
    ls = '0123456789'
    f = open('pwd.txt', 'w')
    for i in ls:
        for j in ls:
            for k in ls:
                for x in ls:
                    for y in ls:
                        for z in ls:
                            for m in ls:
                                for n in ls:
                                    f.write(i+j+k+x+y+z+m+n+'
    ')
    f.close()
    t2 = time.time()
    print(t2-t1)
    # 80.10285377502441
    

    对比

    总计用时

    方法选择用时(单位:秒)
    迭代器62.58520317077637
    嵌套for循环80.10285377502441

    代码风格

    • 迭代器:代码很短,风格良好。
    • 嵌套for循环:代码较长,且for循环的层层嵌套导致代码风格很差,不推荐。

    结果

    对比可见,用迭代器生成密码字典速度更快,且代码风格更加良好。

  • 相关阅读:
    ssh 无密码互通
    React之jsx转js
    分布式事务参考
    js跨域解决方案
    idea编译时JDK版本变化
    计数算法
    Rocketmq消息持久化
    rocketmq安装
    nginx高可用配置
    nginx负载均衡设置
  • 原文地址:https://www.cnblogs.com/ghgxj/p/14219070.html
Copyright © 2011-2022 走看看