python高效使用06_while_True和while_1哪个效率更高

总结:
- 从字节码上来看,两者应该是等效的。但是从实际测试中来看,while True可能比while 1稍微高效一些。
 - 为什么会出现这种情况呢?在python2中True不是关键字,True会转化成1之后在进行对比,字节码会比1多,运行效率会慢。但是在python3中,True是关键字,两者的字节码是一样的,但是关键字经过优化,会比整数1效率高一些。
 
import dis
def run_1():
    while True:
        print("run_1")
        break
def run_2():
    while 1:
        print("run_2")
        break
dis.dis(run_1)
print("-------------------------------------")
dis.dis(run_2)
 
效率对比代码:
import time
# import sys
# import numpy as np
# import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Bar
def test_func_time(n_rows, n_times=100):
    a = time.perf_counter()
    for j in range(n_times):
        for _i in range(n_rows):
            pass
    b = time.perf_counter()
    for_loop_time = (b - a) / n_times
    # 测试while_true
    a = time.perf_counter()
    for j in range(n_times):
        for _i in range(n_rows):
            while True:
                break
    b = time.perf_counter()
    while_true_time = (b - a) / n_times - for_loop_time
    # 测试while_1
    a = time.perf_counter()
    for j in range(n_times):
        for _i in range(n_rows):
            while 1:
                break
    b = time.perf_counter()
    while_1_time = (b - a) / n_times - for_loop_time
    value = round(while_true_time / while_1_time, 4)
    return [value, 1]
if __name__ == '__main__':
    index_list = ["一千行", "一万行", "10万行", "100万行"]
    result = []
    for i in [1000, 10000, 100000, 1000000]:
        r1 = test_func_time(n_rows=i, n_times=1000)
        result.append(r1)
    c = (
        Bar()
        .add_xaxis(index_list)
        .add_yaxis("while True占用时间", [i[0] for i in result])
        .add_yaxis("while 1占用时间", [i[1] for i in result])
        .reversal_axis()
        .set_series_opts(label_opts=opts.LabelOpts(position="right"))
        .set_global_opts(title_opts=opts.TitleOpts(title="以while_1为基准,while_True效率"))
        # .render("d:/result/夏普率耗费时间对比.html")
        .render("./while_True和while_1的效率对比.html")
    )
                