在 C++ 和 Python 之间交换数据的最快方法?

Fastest way to exchange data between C++ and Python?

我正在开发一个用 C++ 和 Python 编写的项目。双方之间的通信是通过 TCP 套接字进行的。两个进程 运行 在同一台机器上。

问题是它对于当前的需求来说太慢了。在 C++ 和 Python 之间交换信息的最快方法是什么?

我听说过 ZeroMQ,但它会比普通 TCP 套接字快得多吗?

编辑:OS 是 Linux,应该传输的数据包含多个浮点数(假设大约 100 个数字),每 0.02 秒一次,双向。所以每秒 50 次,python 代码向 C++ 发送 100 个浮点数,然后 C++ 代码响应 100 个浮点数。

如果性能是您关心的唯一指标,共享内存将是在同一台机器上的两个进程之间共享数据的最快方式 运行。您可以在共享内存中使用信号量进行同步。

TCP 套接字也可以工作,而且速度可能足够快。既然你用的是Linux,我就用管道,这是最简单的方法,他们会outperform TCP sockets. This should get your started: http://man7.org/linux/man-pages/man2/pipe.2.html

更多背景资料,推荐Advanced Programming in the UNIX Environment

简短的回答,不,但是 ZeroMQ 可以有其他优势。让我们直接开始吧,如果你在 Linux 并且想要快速数据传输,你就去 Shared memory。但它不会像 ZeroMQ 那样容易。

因为ZeroMQ是一个消息队列。它解决(并很好地解决)了不同的问题。它能够使用 IPC between C++ and Python, what can be noticeably faster than using sockets (for the same usages), and gives you a window for network features in your future developments. It is reliable and quite easy to use, with the same API in Python and C++. It is often used with Protobuf to serialize and send data,即使是高吞吐量。

ZeroMQ 上 IPC 的第一个问题是它缺少 Windows 支持,因为它不是 POSIX 兼容系统。但最大的问题可能不存在:ZeroMQ is slow because it embeds your message. You can enjoy the benefits of it, but it can impede performances. The best way to check this is, as always, to test it by yourself with IPC-BENCH as I am not sure the benchmark I provided in the previous link was using the IPC. The average gain with IPC 针对本地域的 TCP 并不是很好。

正如我之前所说,我很确定共享内存将是最快的,排除最后一种可能性:开发你自己的 C++ wrapper in Python。我敢打赌这是最快的解决方案,但如果需要,将需要一些多线程工程,因为 C++ 和 Python 将在同一进程上 运行。当然,如果已经启动,则需要调整当前的 C++ 代码。

和往常一样,请记住优化总是在上下文中发生。如果与您之后可以进行的处理相比,数据传输只是 运行ning 时间的一小部分,或者如果您可以等待 0.00001 秒,使用共享内存可以帮助您获得,那么这可能是值得的直接转到 ZeroMQ,因为它会更简单、更具可扩展性和更可靠。

如果你们在同一台机器上,使用命名共享内存,这是一个非常快的选择。在 python 你有 multiprocessing.shared_memory and in C++ you can use posix shared memory,一旦你在 Linux.