簡體   English   中英

診斷並提高計算速度

[英]Diagnosing and improving computation speed

我有一個腳本,它導入了模塊的geometry ,並且此模塊將腳本的速度降低到了極致。 我的腳本生成了一個位圖,並且需要1600萬像素才能花費100多個小時

這里是有問題的模塊:

'''
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在使用上述功能的腳本上提供的統計信息,很明顯,這是花費時間的地方:

   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中)優化它?

實際的時間消耗很可能是您在barycentric_coords進行的矩陣求逆:

    v = np.dot(la.inv(T), np.array(point)-vertices[-1])

記住,在幾乎所有情況下:請不要反轉矩陣!

您可以將該行替換為:

v = np.linalg.lstsq(T, np.array(point)-vertices[-1])[0]

為了獲得更快的最小二乘解相同的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM