Advertisement
borisbn

two test - mmap vs single read

Aug 10th, 2012
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.94 KB | None | 0 0
  1. from ctypes import *
  2. import mmap
  3. import struct
  4. import timeit
  5.  
  6. class SgnHeader(Structure):
  7.     _pack_ = 1
  8.     _fields_ = [ ("ID", c_char * 64),
  9.                  ("headLen", c_ulong),
  10.                  ("RemarkLen", c_ulong),
  11.                  ("usPackingType", c_ushort),
  12.                  ("Squared", c_ushort),
  13.                  ("SampleSize", c_ushort),
  14.                  ("FreqDiskr", c_double),
  15.                  ("dBand", c_double),
  16.                  ("dCF", c_double),
  17.                  ("tSamplesOrigin", c_ulonglong) ]
  18.  
  19. class Ipp16sc(Structure):
  20.     _pack_ = 1
  21.     _fields_ = [ ("re", c_short), ("im", c_short) ]
  22.  
  23. headerLen = sizeof( SgnHeader )
  24. sampleLen = sizeof( Ipp16sc )
  25.  
  26. def doit():
  27.     global headerLen
  28.     global sampleLen
  29.  
  30.     f = open( "d:/InComing/Analiz/file/0_tone.sgn", "r+b" )
  31.     m = mmap.mmap( f.fileno(), 0 )
  32.     header = SgnHeader.from_buffer_copy( m[:headerLen] )
  33.     samplesCount = ( len( m ) - headerLen ) / sampleLen
  34.     s = Ipp16sc * samplesCount
  35.     samples = s.from_buffer_copy( m[headerLen:] )
  36.     for i in samples:
  37.         i.re * i.re + i.im * i.im
  38.     m.close()
  39.     f.close()
  40.  
  41. def doit2():
  42.     global headerLen
  43.     global sampleLen
  44.  
  45.     f = open( "d:/InComing/Analiz/file/0_tone.sgn", "r+b" )
  46.     f.seek(0, 2)
  47.     fileSize = f.tell()
  48.     f.seek(0)
  49.     #print fileSize
  50.  
  51.     headerBytes = f.read( headerLen )
  52.     header = SgnHeader.from_buffer_copy( headerBytes )
  53.    
  54.     structFmt = "=2h"
  55.     s = struct.Struct( structFmt )
  56.     samples = []
  57.     samplesCount = ( fileSize - headerLen ) / sampleLen
  58.     for i in range(samplesCount):
  59.         sampleBytes = f.read( sampleLen )
  60.         samples.append( s.unpack( sampleBytes ) )
  61.  
  62.     for i in samples:
  63.         i[0] * i[0] + i[1] * i[1]
  64.     f.close()
  65.  
  66. from timeit import Timer
  67. t = Timer( "doit()", "from __main__ import doit" )
  68. print t.timeit( number = 10 )
  69. t = Timer( "doit2()", "from __main__ import doit2" )
  70. print t.timeit( number = 10 )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement