我编写了调用子模块数千万次的 perl 代码。子模块是计算密集型的,它的运行时间很慢。我找到了一个完全执行子模块功能的 C++ 程序,我想用 C++ 程序替换子模块。我想知道是否必须编写 XS 代码来接口程序。在 perl 代码中使用“system”命令直接调用 C++ 程序是否会大大降低性能?谢谢!
1 回答
Launching an external program is is always going to be slower than making a function call. If you care about speed, launching a program "tens of millions of times" is out of the question.
If the loop which is executed tens of millions of times is inside the external program, then launching it only once may be acceptable. However, you now have another problem: how to get tens of millions of data to the external program and how to get the results back. Because it's an external program, you'll have to pass the data in text form. This means your script has to transform the data into text, pass it to the external program; the external program has to parse it and transform it into its native representation, perform the calculations, transform the results into text and return it; then your script has to parse the result.
system
is probably not the right tool for this anyway. It is best suited for running programs for their effect (e.g. rm -rf /
) rather than their output. If you want to read the output of a program, you probably want backticks (``
a.k.a. qx{}
) or piping to yourself (see "Using open()
for IPC" in perldoc perlipc
).