V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
geew
V2EX  ›  问与答

这个测试让我有点摸不透了啊, 谁能解释下呢?

  •  
  •   geew · 2013-12-30 10:55:51 +08:00 · 2034 次点击
    这是一个创建于 3920 天前的主题,其中的信息可能已经有所发展或是发生改变。
    代码如下:
    def test(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
    t = time.time()
    func(*args, **kwargs)
    print func.__name__, time.time() - t
    return
    return wrapper


    @test
    def format_test():
    for i in range(_item):
    s = '{a}hello{b}hello{c}'.format(a='wen', b='guo', c='wen')


    @test
    def plus_test():
    for i in range(_item):
    s = 'wen'+'hello'+'guo'+'hello'+'wen'


    @test
    def tuple_test():
    for i in range(_item):
    s = '%shello%shello%s' % ('wen', 'guo', 'wen')


    if __name__ == '__main__':
    format_test()
    plus_test()
    tuple_test()

    结果:
    format_test 0.0439848899841
    plus_test 0.00256514549255
    tuple_test 0.0123269557953


    问题:
    为啥直接加花费的时间要低呢? 这不科学啊, 一直以为它应该是最慢的才对啊啊啊
    3 条回复    1970-01-01 08:00:00 +08:00
    9hills
        1
    9hills  
       2013-12-30 11:16:59 +08:00   ❤️ 1
    1. 标准库有测试工具 http://docs.python.org/2/library/timeit.html 不需要重复造轮子,而且造的还不好

    2. 测试时间尽量达到s级,否则误差太大

    3. +比string format快是正常的,这个还用疑惑?一般来说+的性能比较对象是join。join在大数量级比+快
    binux
        2
    binux  
       2013-12-30 11:24:31 +08:00   ❤️ 1
    +直接被优化掉了
    9hills
        3
    9hills  
       2013-12-30 11:58:18 +08:00
    优化掉+1

    有心情可以测试下
    a=''
    for i in range(1,100000):
    __a += str(i)
    print a

    或者

    a=[]
    for i in range(1, 100000):
    __a.append(str(i))
    print ''.join(a)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5238 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 01:25 · PVG 09:25 · LAX 18:25 · JFK 21:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.