体验内存视图

体验内存视图

https://stackoverflow.com/questions/18655648/what-exactly-is-the-point-of-memoryview-in-python

memoryview是一个内置类,可以实现在不复制内容的条件下高效操作同一个数组的不同切片

1
2
3
4
5
6
7
8
9
import time
for n in (100000, 200000, 300000, 400000):
data = b'x'*n
b = data
start = time.time()
while b:
b = b[1:]
end = time.time()
print(end-start)
0.1373758316040039
0.5009992122650146
1.2156774997711182
2.221696615219116
1
2
3
4
5
6
7
8
for n in (100000, 200000, 300000, 400000):
data = b'x'*n
start = time.time()
b = memoryview(data)
while b:
b = b[1:]
end = time.time()
print(end-start)
0.01299595832824707
0.024030685424804688
0.03499794006347656
0.04696965217590332

一些细节

一个python对象的布尔值取决于它的类中__bool__方法和__len__方法的实现方式. 如果类实现了__bool__方法,则这个类的实例的布尔值就是__bool__方法的返回值. 如果__bool__方法没有实现,则取决于__len__方法的返回值.

1
2
3
4
5
class Toy1:
def __bool__(self):
return True
def __len__(self):
return False
1
2
if Toy1():
print('chichi')
chichi
1
2
3
class Toy2:
def __len__(self):
return False
1
2
if not Toy2():
print('chichi')
chichi