首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >诊断与提高计算速度

诊断与提高计算速度
EN

Stack Overflow用户
提问于 2014-02-06 16:10:55
回答 1查看 213关注 0票数 1

我有一个导入模块geometry的脚本,这个模块将我的脚本降低到一个极端的水平。我的脚本生成1,600万像素的位图和,它需要100+小时

在这里,有问题的模块:

代码语言:javascript
复制
'''
Created on 2 fevr. 2014

@author: gary
'''
#module name is: geometry.py

import numpy as np
import numpy.linalg as la
import tetgen

def barycentric_coords(vertices, point):
    T = (np.array(vertices[:-1])-vertices[-1]).T
    v = np.dot(la.inv(T), np.array(point)-vertices[-1])
    v.resize(len(vertices))
    v[-1] = 1-v.sum()
    #print vertices
    return v

def tetgen_of_hull(points):
    tg_all = tetgen.TetGen(points)

    hull_i = set().union(*tg_all.hull)
    hull_points = [points[i] for i in hull_i]

    tg_hull = tetgen.TetGen(hull_points)
    return tg_hull, hull_i

def containing_tet(tg, point):
    for tet in tg.tets:
        verts = [tg.points[j] for j in tet]
        bcoords = barycentric_coords(verts, point)
        if (bcoords >= 0).all():
            return bcoords
    return None, None

这是cProfile在我的脚本上提供的数据,它使用了上面的函数,显然这就是花费时间的地方:

代码语言:javascript
复制
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1291716   45.576    0.000  171.672    0.000 geometry.py:10(barycentric_coords)

  6460649   31.617    0.000   31.617    0.000 {numpy.core.multiarray.array}
  2583432   15.979    0.000   15.979    0.000 {method 'reduce' of 'numpy.ufunc'
objects}
     2031   12.032    0.006  193.333    0.095 geometry.py:26(containing_tet)
  1291716   10.944    0.000   58.323    0.000 linalg.py:244(solve)
  1291716    7.075    0.000    7.075    0.000 {numpy.linalg.lapack_lite.dgesv}
  1291716    5.750    0.000    9.865    0.000 linalg.py:99(_commonType)
  2583432    5.659    0.000    5.659    0.000 {numpy.core.multiarray._fastCopyAn
dTranspose}
  1291716    5.526    0.000    7.299    0.000 twodim_base.py:169(eye)
  1291716    5.492    0.000   12.791    0.000 numeric.py:1884(identity)

所以我的问题是:

在这里,numpy在处理重心坐标的计算上似乎很慢,在c++中这样做值得吗?或者是否有其他方法(在python中)对此进行优化?

EN

回答 1

Stack Overflow用户

发布于 2014-02-06 23:06:45

实时接收器很可能是你在barycentric_coords中做的矩阵反演。

代码语言:javascript
复制
    v = np.dot(la.inv(T), np.array(point)-vertices[-1])

记住,在几乎所有的情况下:别把那个矩阵颠倒过来!

您可以将这一行替换为:

代码语言:javascript
复制
v = np.linalg.lstsq(T, np.array(point)-vertices[-1])[0]

用一个更快的最小二乘解得到同样的结果。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21608102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档