简体   繁体   English

从Python调用C Math函数的高效解决方案

[英]Efficient Solution for Calling C Math Functions from Python

I have heard about different ways to call C functions from Python code, such as ctypes, cython, swig, Boost.python, etc. Each has pros and cons, of course. 我听说过从Python代码调用C函数的不同方法,比如ctypes,cython,swig,Boost.python等。当然,每个方法都有优缺点。 My question is about efficiency. 我的问题是关于效率。 I need to call C numerical functions from Python. 我需要从Python调用C数值函数。 A typical example of such a C function is: 这种C函数的典型示例是:

double f(double x){
  return sin(x)+cos(x)-pow(2,x) + x*x;
}

The invocation needs to be iterated 2000-200000 times in one run. 调用需要在一次运行中迭代2000-200000次。

Under such context, which C->Python transformer should I use? 在这种情况下,我应该使用哪种C->Python变换器?

Calling a function implemented in C will not magically make your program run faster. 调用用C实现的函数不会神奇地使程序运行得更快。 Not executing code written in Python might speed your program up. 不执行用Python编写的代码可能会加速您的程序。 So you won't gain anything significant by moving such a simple function into a C routine. 因此,通过将这样一个简单的函数移动到C例程中,您将无法获得任何重要信息。 If you call it in a tight loop, the function itself might be fast but the overhead of the loop written in Python will completely dominate. 如果你在一个紧凑的循环中调用它,函数本身可能很快,但用Python编写的循环的开销将完全占主导地位。 So the general idea is to move tasks as large as possible into a C routine. 因此,一般的想法是将尽可能大的任务移动到C例程中。 In your example, this might be the entire loop. 在您的示例中,这可能是整个循环。 Once the chunk of work you do with a single call to a C function is large enough, the function call overhead itself will become negligible so you shouldn't worry about it that much. 一旦你用一个C函数调用完成的工作量足够大,函数调用开销本身就会变得微不足道,所以你不必担心这么多。 Call the function however you find it most convenient. 调用该功能,但您觉得最方便。 Chances are high that it doesn't affect performance in a measurable way. 机会很高,它不会以可衡量的方式影响性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM