geew
V2EX  ›  问与答

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

  •  
  •   geew · Dec 30, 2013 · 2431 views
    This topic created in 4527 days ago, the information mentioned may be changed or developed.
    代码如下:
    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 replies    1970-01-01 08:00:00 +08:00
    9hills
        1
    9hills  
       Dec 30, 2013   ❤️ 1
    1. 标准库有测试工具 http://docs.python.org/2/library/timeit.html 不需要重复造轮子,而且造的还不好

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

    3. +比string format快是正常的,这个还用疑惑?一般来说+的性能比较对象是join。join在大数量级比+快
    binux
        2
    binux  
       Dec 30, 2013   ❤️ 1
    +直接被优化掉了
    9hills
        3
    9hills  
       Dec 30, 2013
    优化掉+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)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   892 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 20:21 · PVG 04:21 · LAX 13:21 · JFK 16:21
    ♥ Do have faith in what you're doing.