Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
序列化python列表的性能_Python_Performance_Wsgi - Fatal编程技术网

序列化python列表的性能

序列化python列表的性能,python,performance,wsgi,Python,Performance,Wsgi,我在Python的性能方面遇到了一些问题。在我的wsgi应用程序中,我将序列化为类的json列表。这是我的代码: class Foo (object): def __init__(self, id,object_id, name_id,name,val,val2): self.id = id self.object_id = object_id self.name_id = name_id self.name = nam

我在Python的性能方面遇到了一些问题。在我的wsgi应用程序中,我将序列化为类的json列表。这是我的代码:

class Foo (object):
    def __init__(self, id,object_id, name_id,name,val,val2):
        self.id = id
        self.object_id = object_id 
        self.name_id = name_id 
        self.name = name
        self.val = val 
        self.add_val = val2


def application(environ, start_response):
        status = '200 OK'
        q = list()
        response_headers = [('Content-type', "application/json")]
        start_response(status, response_headers)
        for i in range(1,50001):
            p = Foo(str(i),random.random(), 'col_3','col_4','col_5','col_6')
            q.append(p.__dict___)
        return json.dumps(q)
我得到的答案很慢(大约18秒)。然后我将代码重写为:

class Foo (object):
    def __init__(self, id,object_id, name_id,name,val,val2):
        self.id = id
        self.object_id = object_id 
        self.name_id = name_id 
        self.name = name
        self.val = val 
        self.add_val = val2


def application(environ, start_response):
        status = '200 OK'
        q = list()
        response_headers = [('Content-type', "application/json")]
        start_response(status, response_headers)
        yield '['
        for i in range(1,50001):
            p = Foo(str(i),random.random(), 'col_3','col_4','col_5','col_6')
            yield json.dumps(p.__dict___)
        yield ']'
它跑得更快(大约4-6秒)。我不明白为什么。你能解释一下为什么我有这个结果吗?
PS我尝试了不同的json LIB,得到了相同的结果。

在我看来,您的第二个版本将缺少几个逗号…我不知道如何实现
json.dumps
,但我认为处理一个非常大的字符串可能会有问题。在这种情况下,您的操作系统需要找到一个足够大的内存块来容纳字符串——如果
json.dumps
正在动态地增加sting,您可能会多次这样做,并在内存中移动大量数据,进行大量分配,等等@mgilson wsgi服务器似乎有问题,因为这两个函数在我的电脑上都运行得非常快。
289毫秒
492毫秒
每个循环分别是的,我想这是有道理的。我不希望
json
像我假设它一定在尝试的那样做有问题的事情:)你是如何安排时间的?它们是否包含某种可能需要很长时间的I/O操作?你在使用线程吗?如果使用多处理器和混合CPU绑定/IO绑定线程,GIL可能会导致I/O的高延迟。