为什么Python protobuf消息的创建这么慢?

Bre*_*tin 5 python protocol-buffers protoc protobuf-python

假设我有一条消息定义为test.proto

\n
message TestMessage {\n    int64 id = 1;\n    string title = 2;\n    string subtitle = 3;\n    string description = 4;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我使用 protoc 将其转换为 Python,如下所示:

\n

protoc --python_out=. test.proto

\n

时间PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python

\n
from test_pb2 import TestMessage\n\n%%timeit\ntm = TestMessage()\ntm.id = 1\ntm.title = 'test title'\ntm.subtitle = 'test subtitle'\ntm.description = 'this is a test description'\n
Run Code Online (Sandbox Code Playgroud)\n

6.75 \xc2\xb5s \xc2\xb1 152 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 100000 loops each)

\n

时间PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=cpp

\n

1.6 \xc2\xb5s \xc2\xb1 115 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000000 loops each)

\n

将其与一个字典进行比较:

\n
%%timeit\ntm = dict(\n    id=1,\n    title='test title',\n    subtitle='test subtitle',\n    description='this is a test description'\n)\n
Run Code Online (Sandbox Code Playgroud)\n

308 ns \xc2\xb1 2.47 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000000 loops each)

\n

这也仅针对一条消息。对于我的整个项目来说,Protobuf cpp 实现大约需要 10.6\xc2\xb5s。

\n

有没有办法让它更快?也许编译输出 ( test_pb2)?

\n