使用以下代码加载模型文件需要相当长的时间:
with open(file_path, "r") as model_file:
triangles = []
vertices = []
texcoords = []
normals = []
use_normals = 1
for line in model_file.readlines():
line = line.strip()
if len(line) == 0 or line.startswith("#"):
continue
data = line.split(" ")
if data[0] == "v":
vertices.append(map(float, data[1:4]))
if data[0] == "vt":
texcoords.append(map(float, data[1:3]))
if data[0] == 'vn':
normalv = map(float, data[1:4])
normalv = normalv[0], normalv[2], normalv[1]
normals.append(normalv)
use_normals = 1
if data[0] == "f":
texture1 = 0
texture2 = 0
texture3 = 0
normal1 = 0
normal2 = 0
normal3 = 0
vertex1 = vertices[int(data[1].split("/")[0]) - 1]
vertex2 = vertices[int(data[2].split("/")[0]) - 1]
vertex3 = vertices[int(data[3].split("/")[0]) - 1]
if len(data[1].split('/')) >= 2 and len(data[1].split('/')[1]) > 0:
texture1 = texcoords[int(data[1].split("/")[1]) - 1]
texture2 = texcoords[int(data[2].split("/")[1]) - 1]
texture3 = texcoords[int(data[3].split("/")[1]) - 1]
if len(data[1].split('/')) >= 3 and len(data[1].split('/')[1]) > 0 and len(data[1].split('/')[2]) > 0:
normal1 = normals[int(data[1].split("/")[2]) - 1]
normal2 = normals[int(data[2].split("/")[2]) - 1]
normal3 = normals[int(data[3].split("/")[2]) - 1]
triangles.append((vertex1, vertex2, vertex3, texture1, texture2, texture3, normal1, normal2, normal3))
gl_list = glGenLists(1)
glNewList(gl_list, GL_COMPILE)
glBegin(GL_TRIANGLES)
i = 0
use_normals = 0
for triangle in triangles:
if use_normals:
glNormal3f(triangle[6][0], triangle[6][1], triangle[6][2])
glTexCoord2f(triangle[3][0], triangle[3][1])
glVertex3f(triangle[0][0], triangle[0][1], triangle[0][2])
if use_normals:
glNormal3f(triangle[7][0], triangle[7][1], triangle[7][2])
glTexCoord2f(triangle[4][0], triangle[4][1])
glVertex3f(triangle[1][0], triangle[1][1], triangle[1][2])
if use_normals:
glNormal3f(triangle[8][0], triangle[8][1], triangle[8][2])
glTexCoord2f(triangle[5][0], triangle[5][1])
glVertex3f(triangle[2][0], triangle[2][1], triangle[2][2])
i += 1
glEnd()
glEndList()
return gl_list
如何优化此代码?我运行cProfile和pstats来获取最难的代码:
41558 0.013 0.000 0.013 0.000 {method 'split' of 'str' objects}
15389 0.006 0.000 0.008 0.000 error.py:206(glCheckError)
3087 0.005 0.000 0.005 0.000 {map}
7 0.003 0.000 0.004 0.001 baseplatform.py:400(__call__)
15385 0.002 0.000 0.002 0.000 error.py:203(nullGetError)
1 0.001 0.001 0.001 0.001 {method 'readlines' of 'file' objects}
5664 0.001 0.000 0.001 0.000 {method 'startswith' of 'str' objects}
18477 0.001 0.000 0.001 0.000 {len}
5657 0.001 0.000 0.001 0.000 {method 'strip' of 'str' objects}
5651 0.001 0.000 0.001 0.000 {method 'append' of 'list' objects}
看起来分割,剥离和数组的代码花费了大部分时间,但是如何用更有效的代码替换代码呢?