简体   繁体   English

加快Python中简单多项式表达式的求值速度

[英]Speed up evaluation of simple polynomial expression in Python

I've written a rather large Python program to do some analysis of data given in the form of a list of cubic Bezier splines. 我编写了一个相当大的Python程序来对以三次贝塞尔曲线样条列表形式给出的数据进行一些分析。 It's very slow and, much to my surprise, after profiling I found that most of the time is spent in the following quite simple function. 这很慢,而且让我感到惊讶的是,在进行性能分析后,我发现大部分时间都花在了以下非常简单的功能上。

    def point(P0,P1,P2,P3,t):
        return ((1-t)**3 * P0) + \
               (3 * (1-t)**2 * t * P1) + \
               (3 * (1-t) * t**2 * P2) + \
               (t**3 * P3)

where t is a float and P0, P1, P2, and P3 are complex numbers. 其中t是浮点数,P0,P1,P2和P3是复数。

Attempting to decrease the number of times this function is executed would, I worry, cause me a lot of headache and might reduce accuracy of my results, so before I try that I'm wondering if anyone knows of a simple way to speed this up. 我担心,尝试减少执行该函数的次数会令我头疼,并且可能会降低结果的准确性,因此在尝试之前,我想知道是否有人知道一种加快此过程的简单方法。

I've heard I might be able to compile this as a C/C++ function that could be called from my python code, but I've never done something like that (and it's been a long time since I used C/C++ for anything) so I wanted to get an expert opinion before spending time diving into anything like that. 我听说我可以将其编译为可以从我的python代码调用的C / C ++函数,但是我从来没有做过这样的事情(而且自从我将C / C ++用于任何东西已经很长时间了) ),因此我想在花时间深入研究类似问题之前先征求专家意见。

Also, to be thorough, the above function is really a method of the Path class in a module called svg.path. 另外,更确切地说,以上函数实际上是名为svg.path的模块中Path类的方法。 Its exact syntax is as follows. 其确切语法如下。

    def point(self, pos):
        """Calculate the x,y position at a certain position of the path"""
        return ((1-pos) ** 3 * self.start) + \
               (3 * (1-pos) ** 2 * pos * self.control1) + \
               (3 * (1-pos) * pos ** 2 * self.control2) + \
               (pos ** 3 * self.end)

If you replace ** by * and factor the polynomial like: 如果将**替换为*并分解多项式,例如:

def point(P0, P1, P2, P3, t):
    return P0 + \ 
        t * (3 * (P1 - P0) + \
        t * (3 * (P0 + P2) - 6 * P1 + \
        t * (-P0 + 3 * (P1 - P2) + P3)))

You gain nearly a factor 2 in performance. 您将性能提高近2倍。

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

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