二、字符串与整数拼接速度对比(Python中的AI对比实验)
完整代码如下:
# -*- coding: UTF-8 -*-
# Author: Perry
# @Create Time: 2020-04-06 14:55
import timeit
import numpy as np
def ints():
_ = "str" + str(12)
def ints_f():
_ = "str%d" % 12
def floats():
_ = "str" + str(12.33)
def floats_f():
_ = "str%f" % 12.33
def strs():
_ = "str" + "12.33"
def strs_f():
_ = "str%s" % "12.33"
if __name__ == '__main__':
repeat = 10
number = 100000
int_time = timeit.repeat('ints()', 'from __main__ import ints', repeat=repeat, number=number)
int_time = np.mean(int_time)
print("int_time: ", int_time)
int_f_time = timeit.repeat('ints_f()', 'from __main__ import ints_f', repeat=repeat, number=number)
int_f_time = np.mean(int_f_time)
print("int_f_time: ", int_f_time)
float_time = timeit.repeat('floats()', 'from __main__ import floats', repeat=repeat, number=number)
float_time = np.mean(float_time)
print("float_time: ", float_time)
float_f_time = timeit.repeat('floats_f()', 'from __main__ import floats_f', repeat=repeat, number=number)
float_f_time = np.mean(float_f_time)
print("float_f_time: ", float_f_time)
str_time = timeit.repeat('strs()', 'from __main__ import strs', repeat=repeat, number=number)
str_time = np.mean(str_time)
print("str_time: ", str_time)
str_f_time = timeit.repeat('strs_f()', 'from __main__ import strs_f', repeat=repeat, number=number)
str_f_time = np.mean(str_f_time)
print("str_f_time: ", str_f_time)
输出结果:
int_time: 0.02541184720000001
int_f_time: 0.01889225879999996
float_time: 0.04497297539999997
float_f_time: 0.0266983679
str_time: 0.006410686699999979
str_f_time: 0.01752534760000002
结论:当有类型转换的时候,使用 % 转换更快;否则,若为str
,则用+
更快。