我需要一个在Python中随机w/r文本片段的快速解决方案。我想这样做:
代码片段的长度是任意的,我选择不使用数据库来存储它们,而只使用指针。通过简单地用C函数替换Python文件方法(解决方案1),它的速度非常快,指针只包含代码片段的“where”和“how long”。在那之后,我做了一个实验,我认为这是与伯克利数据库一起工作的真正的东西。我不知道该怎么称呼它,也许是“寻呼”之类的东西?在
问题是,这段代码绝对可以工作,比解决方案1快1.5到2倍,但速度不是很快,需要使用4部分指针。也许这不是一个值得的方法,但是否有任何空间来显著改进它?
代码如下:
from collections import namedtuple
from ctypes import cdll,c_char_p,\
c_void_p,c_size_t,c_long,\
c_int,create_string_buffer
libc = cdll.msvcrt
fopen = libc.fopen
fread = libc.fread
fwrite = libc.fwrite
fseek = libc.fseek
ftell = libc.ftell
fflush = libc.fflush
fclose = libc.fclose
#######################################################
# The following is how to write a snippet into the SnippetBase file
ptr = namedtuple('pointer','blk1, start, nblk, length')
snippet = '''
blk1: the first blk where the snippet is
start: the start of this snippet
nblk: number of blocks this snippet takes
length: length of this snippet
'''
bsize = 4096 # bsize: block size
fh = fopen('.\\SnippetBase.txt','wb')
fseek(fh,0,2)
pos1 = divmod(ftell(fh),bsize)
fwrite(snippet,c_size_t(len(snippet)),1,fh)
fflush(fh)
pos2 = divmod(ftell(fh),bsize)
ptr = ptr(pos1[0],pos1[1],pos2[0]-pos1[0]+1,len(snippet))
fclose(fh)
#######################################################
# The following is how to read the snippet from the SnippetBase file
fh = fopen('.\\SnippetBase.txt','rb')
fseek(fh,c_long(ptr.blk1*bsize),1)
buff = create_string_buffer(ptr.nblk*bsize)
fread(buff,c_size_t(ptr.nblk*bsize),1,fh)
print buffer(buff,ptr.start,ptr.length)
fclose(fh)
这看起来像是一种硬而不可移植的方法来优化一件事——由Python包装器^{} 和{a2}执行的内存分配。所有其他部分都可以使用Python标准库中已有的函数轻松完成。甚至还有一个简单的方法可以在^{} 中分配读/写缓冲区。} ,它存在于文件类型中;我高度怀疑这确实避免了分配。然而,在最流行的操作系统上,我们可以更进一步—直接使用操作系统磁盘缓冲区,而不是为进程分配本地内存。这是使用^{} 完成的(但是当文件太大而无法容纳您的地址空间时,使用它会变得很麻烦)。对于从mmaped文件中读取数据的非分配方法,只需使用^{} 。在
io
模块确实包含一个方法^{相关问题 更多 >
编程相关推荐