Bre*_*tin 5 python protocol-buffers protoc protobuf-python
假设我有一条消息定义为test.proto:
message TestMessage {\n int64 id = 1;\n string title = 2;\n string subtitle = 3;\n string description = 4;\n}\nRun Code Online (Sandbox Code Playgroud)\n我使用 protoc 将其转换为 Python,如下所示:
\nprotoc --python_out=. test.proto
时间PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python:
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'\nRun Code Online (Sandbox Code Playgroud)\n6.75 \xc2\xb5s \xc2\xb1 152 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 100000 loops each)
时间PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=cpp:
1.6 \xc2\xb5s \xc2\xb1 115 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000000 loops each)
将其与一个字典进行比较:
\n%%timeit\ntm = dict(\n id=1,\n title='test title',\n subtitle='test subtitle',\n description='this is a test description'\n)\nRun Code Online (Sandbox Code Playgroud)\n308 ns \xc2\xb1 2.47 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000000 loops each)
这也仅针对一条消息。对于我的整个项目来说,Protobuf cpp 实现大约需要 10.6\xc2\xb5s。
\n有没有办法让它更快?也许编译输出 ( test_pb2)?