`
54yuri
  • 浏览: 27934 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

python 性能测试(1)-- % vs + vs str.join vs +=

阅读更多
网上广为流传着"不要使用+" 连接字符串的“经验”, 特别是这篇文章当中提到了
http://www.oschina.net/question/129540_61768

引用
要使用 out = "<html>%s%s%s%s</html>" % (head, prologue, query, tail)
而避免 out = "<html>" + head + prologue + query + tail + "</html>"


-------

实际上果真如此吗? 连接字符串主要有四种用法:
  • %
  • +
  • str.join
  • +=


我的理解是这样的
% 和 + 都是应付参数个数已知的、固定的,比如已经知道了a,b,c 三个参数了,那么a+b+c
str.join 和 += 主要是应付参数个数未知的、不固定的,比如参数的一个列表当中所有的字符串,这个列表长度未知;当然他们也可以应付参数个数固定的情况


我的开发环境是:
CPU:  Intel(R) Xeon(R) E5520  @ 2.27GHz
Memory: 2G
OS: Ubuntu 12.04


第1回合使用
解释器:python 2.7.3

'use % to join' run 1000000 times, spent 2.045571 seconds
'use + ' run 1000000 times, spent 2.238076 seconds

'use str.join ' run 1000000 times, spent 1.816502 seconds

'use += ' run 1000000 times, spent 3.134726 seconds
-----
long items test:
'use % to join' run 1000000 times, spent 3.631465 seconds
'use + ' run 1000000 times, spent 3.203789 seconds

'use str.join ' run 1000000 times, spent 2.474077 seconds
'use += ' run 1000000 times, spent 3.927131 seconds




第2回合使用 pypy, 鉴于使用pypy的人多了起来, 这回是使用ubuntu12 自带的 pypy 1.8
解释器:pypy 1.8 (== python 2.7.2)

short items test:
'use % to join' run 1000000 times, spent 1.637780 seconds
'use + ' run 1000000 times, spent 1.498548 seconds

'use str.join ' run 1000000 times, spent 2.204772 seconds
'use += ' run 1000000 times, spent 2.955786 seconds
-----
long items test:
'use % to join' run 1000000 times, spent 3.570450 seconds
'use + ' run 1000000 times, spent 1.730548 seconds

'use str.join ' run 1000000 times, spent 2.914669 seconds
'use += ' run 1000000 times, spent 5.924469 seconds




第3回合使用 最新的PyPy 2.0 beta1
解释器:pypy 2.0 beta1 (== python 2.7.3)

short items test:
'use % to join' run 1000000 times, spent 0.749635 seconds
'use + ' run 1000000 times, spent 0.423104 seconds

'use str.join ' run 1000000 times, spent 1.319862 seconds
'use += ' run 1000000 times, spent 1.985512 seconds
-----
long items test:
'use % to join' run 1000000 times, spent 2.512883 seconds
'use + ' run 1000000 times, spent 0.414724 seconds

'use str.join ' run 1000000 times, spent 1.934615 seconds
'use += ' run 1000000 times, spent 4.973543 seconds



可以下个结论了:
在纯python上,无论长字符串还是短字符串: 参数个数已知 or 参数个数未知, 都用join吧
如果是pypy, 无论长字符串还是短字符串: 参数个数已知用+ , 未知用join吧; BTW, pypy 2.0beta 的速度确实挺快的


无论哪种情况+哪种解释器,的确是不要用 "+=" !




我的测试代码如下(特别感谢提醒“暗能量有点甜”http://www.weibo.com/kyuseishu 的提示,代码更简洁了):
#!/usr/bin/env python
import time


def show_run_time(name, count, func, args):
    start = time.time()
    for i in xrange(count):
        apply(func, [],  args)
 
    print("'%s' run %d times, spent %.6f seconds"%(name, count, time.time()-start))


if __name__ == '__main__':

    count = 1000 * 1000
    args1 = { #short items
        "a": "1"*3,
        "b": "2"*4, 
        "c": "3"*5,
        "d": "4"*6,
        "e": "5"*7,
        "f": "6"*8,
        "g": "7"*9,
        "h": "8"*10,
    }
    

    args2 = { #long items
        "a": "1"*101,
        "b": "2"*131, 
        "c": "3"*161,
        "d": "4"*191,
        "e": "5"*221,
        "f": "6"*251,
        "g": "7"*281,
        "h": "8"*311,
    }


    def test_str_format(a, b, c, d, e, f, g, h):
        out1 = "<html>%s%s%s%s%s%s%s%s</html>" % (a, b, c, d, e, f, g, h)
        out2 = "<table>%s%s%s%s%s%s%s%s</table>" % (h, b, c, d, e, f, g, a)
        return  ("%s | %s"%(out1, out2))

    def test_plus(a, b, c, d, e, f, g, h):
        out1 = "<html>" + a + b  + c + d + e + f + g + b + "</html>"
        out2 = "<table>" + h + b  + c + d + e + f + g + a + "</table>"
        return  out1 + " | " + out2

    def test_plus_and_equal(a, b, c, d, e, f, g, h):
        out = "<html>"
        for i in [a, b, c, d, e, f, g, h]:
             out += i
        out += "</html> | <table>"

        for i in [h, b, c, d, e, f, g, a]:
             out += i
        out += "</table>"

        return out


    def test_join(a, b, c, d, e, f, g, h):
        out1 = "".join(["<html>", a, b, c, d, e, f, g, h, "</html>"])
        out2 = "".join(["<table>", h, b, c, d, e, f, g, a, "</table>"])
        return  " | ".join((out1, out2))

    print "short items test:"
    show_run_time("use % to join", count, test_str_format, args1)
    show_run_time("use + ", count, test_plus, args1)

    show_run_time("use str.join ", count, test_join, args1)
    show_run_time("use += ", count, test_plus_and_equal, args1)

    print "-----"

    print "long items test:"
    show_run_time("use % to join", count, test_str_format, args2)
    show_run_time("use + ", count, test_plus, args2)

    show_run_time("use str.join ", count, test_join, args2)
    show_run_time("use += ", count, test_plus_and_equal, args2)
    
    
分享到:
评论

相关推荐

    python-str函数用法.doc

    Python中的`str()`函数是将其他数据类型转换成字符串的关键工具。这个函数广泛应用于各种场景,包括输出、格式化和文本处理。以下是对`str()`函数及其相关扩展的详细解释。 1. **基本使用**: `str()`函数接受一个...

    头歌python程序设计答案-07-字符串拼接.ev4.rar

    在Python编程语言中,字符串是数据处理的核心部分,特别是在各种编程任务中,如文本分析、数据清洗、报告生成等。本资源"头歌python程序设计答案-07-字符串拼接.ev4.rar"可能是一个教学视频或课程资料,专注于讲解...

    自己使用总结Python程序代码片段

    file_out = str('_'.join(line.split())) + postfix # 使用split和join生成文件名 with open(file_out, 'w') as fout: # 以写的方式打开文件 fout.write(line.strip()) # 写入内容 ``` **知识点:** 1. **with...

    赵璐python教程答案-Python学习习题笔记-基础篇.pdf

    1. 字符串操作:在Python中,字符串是不可变数据类型,意味着一旦创建就不能直接修改。尝试对字符串的某个位置赋值,如`info[2] = 'd'`会引发`TypeError`,因为字符串不支持这样的操作。 2. 替换字符串中的字符: ...

    试卷NCT-Python编程三级-模拟卷4(含答案程序填空阅读填空程序试题.docx

    print(', '.join(str(num) for num in result)) ``` 13. **字符串转换** 将输入的字符串转换为大写,可以使用`str.upper()`方法: ```python user_input = input("请输入数据:") uppercase_data = user_...

    Python中str.join()简单用法示例

    在Python编程语言中,`str.join()`方法是一个非常实用的功能,它允许我们高效地将一个序列(如列表、元组等)中的多个...在学习Python字符串操作时,掌握`str.join()`是非常关键的一步,它能够提高代码的可读性和性能。

    Python语言教程2-python批量图片大小处理-多文件夹

    ss = './1/' + str(files[b]) + '/' pics = os.listdir(ss) i = 1 for each_bmp in pics: ``` 使用`while`循环遍历每个子文件夹,并获取其中的所有图片名称。 4. **图片处理逻辑**: ```python first_name,...

    Python库 | PyPika-0.37.8.tar.gz

    **Python库PyPika概述** PyPika是一个轻量级且高效的SQL构建库,专为Python设计,用于简化与MySQL数据库的交互。它提供了一种简单、直观的方式来构造和执行SQL查询,避免了直接字符串拼接带来的潜在错误和不安全性...

    从零学Python,python-Day02.rar

    在Python编程语言的学习旅程中,"Day02"通常是初学者深入接触基础知识的关键阶段。这个压缩包文件"python-Day02.rar"很可能包含了第二天课程的所有资料,帮助学习者巩固第一天的知识并逐步掌握更多Python概念。让...

    python导出剪映字幕为srt.py

    python 实现 PC端剪映字幕转换SRT格式工具代码-Python 实现,# -*- coding: utf-8 -*- import getpass import os import json import re def get_time(time_int): # 使用正则表达式处理时间格式化问题 if time_...

    Python源码自动办公-13 用Python批量重命名文件.rar

    在IT行业中,自动化办公是提高效率的关键之一,Python作为一种强大的编程语言,因其简洁易学的语法和丰富的库支持,常被用于实现各种自动化任务,包括批量重命名文件。本资料"Python源码自动办公-13 用Python批量...

    python二级模拟试卷1程序填空阅读填空程序试题.doc

    result = ', '.join(str(year) for year in range(2000, 3201) if year % 7 == 0 and year % 5 != 0) print(result) ``` 8. 排序成绩: 输入三个成绩,可以使用内置的sorted函数对成绩进行排序,然后依次输出。 `...

    python开发常见语法处理

    ### Python开发中的常见语法处理 Python作为一种广泛应用的编程语言,在数据处理、Web开发以及科学计算等领域都有着出色的表现。本文将围绕“Python开发常见语法处理”这一主题,详细讲解包括字符替换、字符截取、...

    python_str_python_

    在Python编程语言中,字符串(str)是一种基本的数据类型,用于存储文本信息。字符串是不可变的,这意味着一旦创建,就不能直接修改字符串中的单个字符。以下是对字符串操作的详细说明: 1. **创建字符串**:你可以...

    python教程-01-第二天知识点回顾.ev4.rar

    1. **变量与数据类型**:Python中的变量是存储值的容器,可以是整数、浮点数、字符串等。基础数据类型包括int、float、str、bool等。了解如何声明和使用这些变量是学习Python的第一步。 2. **运算符**:Python支持...

    python中字符串方法.docx

    str3 = "".join([str1, str2]) print(str3) # 输出 "HelloWorld" ``` 2. **字符串的替换**: - `replace()`方法用于替换字符串中的某个子串。例如: ```python str1 = "Hello World" str2 = str1.replace(...

    pythonjoin的用法.docx

    Python中的`join()`函数是字符串操作的一个核心方法,它允许我们将序列(如列表、元组、集合或字典)中的元素连接成一个单一的字符串。这个功能在处理文本数据时尤其有用,例如在生成报告、格式化输出或者构建复杂的...

    信息技术考试卷 python.docx

    - 字符串(str)可以拼接,如`"Python", "语言"`。 - 元组(tup)可以用逗号分隔创建,也可以用`.join()`方法连接,如`("123", "234")`。 - 集合(set)可以进行并集操作,但`{1, 2, 3} + {4, 5, 6}`是错误的,因为集合...

    华为OD机试C卷- 考古学家(Java & JS & Python).md-私信看全套OD代码及解析

    ### 华为OD机试C卷 - 考古学家(Java & JS & Python) #### 题目背景与需求 本题目源自华为OD(Outsourcing Development)机试的一道编程题,主要考察应聘者在Java、JavaScript、Python三种语言下的编程能力,特别...

Global site tag (gtag.js) - Google Analytics