问题描述
我需要一个给定的结构,我必须使用它进行大量的添加/弹出操作,访问值并进行计算。 我将不得不不断地进行操作以更新我的数据。
我首先看了将在dic中的python列表。 主要问题是计算速度很慢,即使是简单的总和也要花费时间。
我看过numpy端,但是append / pop很长(尽管我不认为numpy是个好主意),甚至访问值也不是那么快。
我求助于cython来保持列表/字典的性能,从而提高了我的代码的性能,但是性能总是很慢。
所以我想到了转向std :: map和std :: vector来做同样的事情,但是速度更快。
我用向量的和进行了测试,即使numpy的速度也较慢,所以我认为我已经找到了所需的结构。 然后我测试了排序,我应该非常定期地进行排序,令人惊讶的是,向量比在python中对列表进行排序要长2-3倍。 经过大量研究,我无法弄清排序向量如此“慢”的原因。
test_cython.pyx
# distutils: language = c++
from libcpp.vector cimport vector
from libcpp.algorithm cimport sort as stdsort
#I tried to import this way but the speed doesn't change.
"""cdef extern from "<algorithm>" namespace "std":
void sort(...)
void stdsort "sort"(...)"""
cdef class VectorSort:
cdef vector[long] v
def __init__(self):
for i in range(100000):
self.v.push_back(i)
def vector_sort(self):
stdsort(self.v.begin(),self.v.end())
cdef class PythonSort:
cdef list l
def __init__(self):
self.l = [i for i in range(100000)]
def python_sort(self):
self.l.sort()
main.py
import timeit
from test_cython import VectorSort,PythonSort
v = VectorSort()
def sort_vector():
v.vector_sort()
l = PythonSort()
def sort_python():
l.python_sort()
print(timeit.timeit('sort_vector()','from __main__ import sort_vector',number=1000),'-> sort_vector')
print(timeit.timeit('sort_python()','from __main__ import sort_python','-> sort_python')
输出:
0.9847416740085464 -> sort_vector
0.3762993350101169 -> sort_python
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)