问题描述
我试图稍微提高一些python代码的速度,因此尝试将标准for循环移动到列表理解或map调用:
I'm trying to improve the speed of some python code a bit and therefore trying to move a standard for loop to either a list comprehension or map call:
buf = [0 for i in range(self.numLEDs * 3)]
temp = [0,0,0]
for x in range(self.numLEDs):
r = data[x*3]
g = data[x*3+1]
b = data[x*3+2]
temp[self.c_order[0]] = self.gamma[r]
temp[self.c_order[1]] = self.gamma[g]
temp[self.c_order[2]] = self.gamma[b]
buf[x * 3:x * 3 + 3] = temp
c_order只是另一个列表,在这种情况下为[1,2,0].它控制某些RGB像素的通道顺序. gamma是一个256个元素的列表,其中包含8位通道值中每个值的经过gamma校正的值.
c_order is simply another list, in this case [1,2,0]. It controls the channel order for some RGB pixels. gamma is a list 256 elements long that holds gamma corrected values for each of the 8bit channel values.
我想做的是以某种方式从这段代码中完全删除对循环标准的使用.我已经设法在没有通道交换的情况下做到了这一点,但是通过伽马校正,它的速度快了一倍.像这样:
What'd I'd like to do is somehow completely remove any use of a standard for loop from this bit of code. I've managed to do it without the channel swap, but with the gamma correction and it's twice as fast. Like this:
corrected = [gamma[i] for i in data]
buf[0:len(corrected)] = corrected
我如何在没有for循环的情况下交换列表元素的顺序?
How can I swap the order of list elements as I go without a for loop though?
推荐答案
因此,您需要没有任何扩展库的纯python代码.
So you need pure python code without any extension library.
要加速代码:
- 在循环中使用局部变量.
- 更改循环以列出理解.
这是代码:
class Test(object):
def __init__(self, n):
self.numLEDs = n
self.c_order = [1, 2, 0]
self.gamma = [i // 2 for i in range(256)]
def do1(self, data):
buf = [0 for i in range(self.numLEDs * 3)]
temp = [0,0,0]
for x in range(self.numLEDs):
r = data[x*3]
g = data[x*3+1]
b = data[x*3+2]
temp[self.c_order[0]] = self.gamma[r]
temp[self.c_order[1]] = self.gamma[g]
temp[self.c_order[2]] = self.gamma[b]
buf[x * 3:x * 3 + 3] = temp
return buf
def do2(self, data):
buf = [0] * (self.numLEDs * 3)
gamma = self.gamma
for idx, idx2 in enumerate(self.c_order):
buf[idx2::3] = [gamma[v] for v in data[idx::3]]
return buf
import random
random.seed(0)
N = 1000
t = Test(N)
data = [random.randint(0, 255) for i in range(3*N)]
r1 = t.do1(data)
r2 = t.do2(data)
print r1 == r2 # check the result
%timeit t.do1(data)
%timeit t.do2(data)
输出,速度提高了6倍:
the output, it's 6x faster:
True
1000 loops, best of 3: 1.1 ms per loop
10000 loops, best of 3: 176 µs per loop
这篇关于for循环列出python中的理解或映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!