2

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

message TestMessage {
    int64 id = 1;
    string title = 2;
    string subtitle = 3;
    string description = 4;
}

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

protoc --python_out=. test.proto

时间PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python

from test_pb2 import TestMessage

%%timeit
tm = TestMessage()
tm.id = 1
tm.title = 'test title'
tm.subtitle = 'test subtitle'
tm.description = 'this is a test description'

6.75 µs ± 152 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

时间PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=cpp

1.6 µs ± 115 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

将其与 dict 进行比较:

%%timeit
tm = dict(
    id=1,
    title='test title',
    subtitle='test subtitle',
    description='this is a test description'
)

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

这也仅适用于一条消息。我的整个项目的 Protobuf cpp 实施大约需要 10.6µs。

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

4

0 回答 0