2014年6月

Python 字典的合并效率

在 Python 编程中,字典的使用频率非常高,合并操作也很常见。

x = {'name':'Eric', 'age':28}
y = {'age':29, 'hobby':['sport', 'travel']}

例如要合并这两个字典:更新其中某项,并添加新项。你能想到什么办法?

  1. update 方法

    z = x.copy()
    z.update(y)

  2. 使用 dict() 函数的字典参数

    z = dict(x, **y)

  3. items 变换

    z = dict(x.items() + y.items())

  4. lambda 表达式

    z = (lambda a, b: (lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(x, y)

这些方法都可以达到要求,哪种效率最高呢?

我们可以使用 timeit 模块来测试它们的运行效率。

import timeit

# 1 update 方法
timeit.timeit("z = x.copy(); z.update(y)", "x = {'name':'Eric', 'age':28}; y = {'age':29, 'hobby':['sport', 'travel']}")
# output: 0.31891608238220215

# 2 使用 dict() 函数的字典参数
timeit.timeit("z = dict(x, **y)", "x = {'name':'Eric', 'age':28}; y = {'age':29, 'hobby':['sport', 'travel']}")
# output: 0.30063605308532715

# 3 items 变换
timeit.timeit("z = dict(x.items() + y.items())", "x = {'name':'Eric', 'age':28}; y = {'age':29, 'hobby':['sport', 'travel']}")
# output: 0.8453028202056885

# 4 lambda 表达式
timeit.timeit("(lambda a, b: (lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(x, y)", "x = {'name':'Eric', 'age':28}; y = {'age':29, 'hobby':['sport', 'travel']}")
# output: 0.6631548404693604

结果显示,方法1和2效率最高,且两者运行时间差不多。其次是方法4,最差的是方法3。(对运行时间的计算,多次运行取平均值会更准确一点。)

总结下来,运行效率用公式表示如下:
1 = 2 > 4 > 3

Nginx + PHP 设置文件上传大小

你可能会碰到服务器 413 错误,当文件上传到服务器时,返回如下结果:

HTTP/1.1 413 Request Entity Too Large

原因

服务器限制了文件上传大小。默认大小,Nginx 为1M,PHP 为2M。因此超过1M便返回413.

如何修改大小限制

需要同时修改 PHP 和 Nginx 的配置。

PHP

编辑 php.ini 文件,找到对应的位置:

; Maximum size of POST data that PHP will accept.
; http://php.net/post-max-size
post_max_size = 10M

; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 8M

post_max_size 指表单 POST 数据的最大值;
upload_max_filesize 指上传文件的最大值;
注意:这个参数 file_uploads = On,确保它是打开的。

Nginx

编辑 nginx.conf 文件或者子配置文件,在 server 段的 location 中配置:

location / {
    root   /home/eric/workspace/GameFeedback/www;
    index  index.html index.htm index.php;
    if (!-e $request_filename) {
        rewrite ^/(.*)$ /index.php?/$1 last;
    }
    client_max_body_size 8m;
}

location ~ \.php$ {
    root           /home/eric/workspace/GameFeedback/www;
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
    client_max_body_size 8m;
}

注意:两个 location 都要配置,否则无效。

最后,需要重启 Nginx 服务;如果是 php-fpm,也要重启以使配置生效。