2012-03-05 2 views
26

मैं एक बाइनरी फ़ाइल विनिर्देश है कि एक पैकेट डेटा संरचना का वर्णन करता है। प्रत्येक डाटा पैकेट एक दो बाइट सिंक पैटर्न है, तो एक पैकेट की शुरुआत के लिए स्कैनिंग एक BinaryReader और FileStream संयोजन का उपयोग संभव है,:मैं बाइनरी फ़ाइल की तेज़ी से स्कैनिंग कैसे कर सकता हूं?

while(!reader.EndOfFile) 
{ 
    // Check for sync pattern. 
    if (reader.ReadUInt16() != 0xEB25) 
    { 
     // Move to next byte. 
     reader.BaseStream.Seek(-1, SeekOrigin.Current); 
     continue; 
    } 

    // If we got here, a sync pattern was found. 
} 

इस प्रक्रिया को आगे की दिशा में पूरी तरह से ठीक काम करता है, लेकिन इसी तरह कोड स्कैनिंग विपरीत दिशा में धीमी परिमाण के कम से कम दो आदेश है:

while(!reader.BeginningOfFile) 
{ 
    // Check for sync pattern. 
    if (reader.ReadUInt16() != 0xEB25) 
    { 
     // Move to previous byte. 
     reader.BaseStream.Seek(-3, SeekOrigin.Current); 
     continue; 
    } 

    // If we got here, a sync pattern was found. 
} 

मैं कुछ समाधान की कोशिश की है एक मनमाना राशि (वर्तमान में 1 मेगाबाइट) से वापस जाने और आगे स्कैनिंग की तरह, है, लेकिन यह है कि स्पष्ट होता जा रहा है क्या मैं वास्तव में जरूरत है एक BinaryReader या FileStream कि हा करने के लिए संशोधित किया गया है आगे और विपरीत दिशाओं में पढ़ने के दौरान पर्याप्त प्रदर्शन विशेषताओं है।

मैं पहले से ही एक FastFileStream जो एक साधारण FileStream उपवर्गीकरण और Position और Length गुण (यह भी BeginningOfFile और EndOfFile गुण प्रदान करता है) कैशिंग द्वारा आगे पढ़ने के प्रदर्शन को बेहतर बनाता है। यही है ऊपर दिए गए कोड में reader चर ड्राइव करता है।

वहाँ कुछ इसी तरह मैं रिवर्स पढ़ने के प्रदर्शन में सुधार करने के लिए, शायद एक MemoryStream एक बफर के रूप को शामिल करके कर सकता है?

+0

'इस प्रक्रिया को आगे direction' में बिल्कुल ठीक काम करता है। यह भी भयानक है। दो बाइट पढ़ें, यदि 'EB25' नहीं है तो एक बाइट बैक लें। –

+0

@ एलबी: वास्तविक कोड को इससे थोड़ा अधिक अनुकूलित किया गया है ... आगे की दिशा में, मैं 0x25 पहले (लिटिल एंडियन का सम्मान करता हूं), और फिर 0xEB के लिए जांच करता हूं। कोड जो मैंने यहां पोस्ट किया है वह स्पष्टता के लिए सरलीकृत है।मेरा विश्वास करो, यह बाइट्स की जांच करने का तरीका नहीं है; विपरीत दिशा में मंदी हो रही है क्योंकि फ़ाइल सिस्टम इस तरह पीछे काम करने के लिए डिज़ाइन नहीं किए गए हैं। –

+0

आपको यहां बहुत भाग्य नहीं मिलेगा। सभी परतें (लीब, ओएस, हार्डवेयर) को आगे पढ़ने के लिए अनुकूलित किया गया है। एक बड़ा कदम वापस लेने का आपका दृष्टिकोण और फिर स्कैन-फॉरवर्ड उचित लगता है। –

उत्तर

15

L.B एक मेमोरी मैप फ़ाइल का उपयोग के लिए एक टिप्पणी में उल्लेख किया है, तो आप प्रदर्शन से प्रभावित हो सकता है।

कुछ इस तरह का प्रयास करें:

var memoryMapName = Path.GetFileName(fileToRead); 

using (var mapStream = new FileStream(fileToRead, FileMode.Open)) 
{ 
    using (var myMap = MemoryMappedFile.CreateFromFile(
          mapStream, 
          memoryMapName, mapStream.Length, 
          MemoryMappedFileAccess.Read, null, 
          HandleInheritability.None, false)) 
    {      
     long leftToRead = mapStream.Length; 
     long mapSize = Math.Min(1024 * 1024, mapStream.Length); 
     long bytesRead = 0; 
     long mapOffset = Math.Max(mapStream.Length - mapSize, 0); 

     while (leftToRead > 1) 
     { 
      using (var FileMap = myMap.CreateViewAccessor(mapOffset, 
           mapSize, MemoryMappedFileAccess.Read)) 
      { 
       long readAt = mapSize - 2; 
       while (readAt > -1) 
       { 
        var int16Read = FileMap.ReadUInt16(readAt); 
        //0xEB25 <--check int16Read here        
        bytesRead += 1; 
        readAt -= 1; 
       } 
      } 

      leftToRead = mapStream.Length- bytesRead; 
      mapOffset = Math.Max(mapOffset - mapSize, 0); 
      mapSize = Math.Min(mapSize, leftToRead); 
     } 
    } 
} 
+0

मैं आगे बढ़ गया और आपका उत्तर उखाड़ फेंक दिया, क्योंकि मुझे लगता है कि यह एक अच्छा है, लेकिन सिर्फ इस बात से अवगत रहें कि इस सवाल पर .NET 3.5 टैग है, और मेरा मानना ​​है कि 'MemoryMappedFile' केवल .NET 4.0 में उपलब्ध है। :) –

+0

निष्पक्ष होने के लिए आप हमेशा 3.5 में मैप किए गए फ़ाइल एपीआई को पी/आमंत्रित कर सकते हैं, इसलिए अगर यह मदद करता है, तो भी आप इसे कुछ मामूली फ़ंक्शन कॉल परिवर्तनों के साथ उपयोग कर सकते हैं। – Blindy

+0

@RobertHarvey आप इसे 3.5 में कर सकते हैं लेकिन आपको [Win32 फ़ंक्शंस को लपेटना होगा] (http://msdn.microsoft.com/en-us/library/aa366781%28v=vs.85%29.aspx#file_mapping_functions) – Jetti

21

संपादित करें: ठीक है, मैं कुछ कोड मिल गया है। खैर, बहुत सारे कोड। यह आपको पैकेट हेडर के लिए आगे और पीछे स्कैन करने की अनुमति देता है।

मुझे कोई गारंटी नहीं है कि इसमें कोई बग नहीं है, और आप निश्चित रूप से बफर आकार को ट्विक करना चाहते हैं कि यह कैसा प्रदर्शन करता है ... लेकिन उसी फ़ाइल को आपने मुझे भेजा है, यह कम से कम उसी पैकेट हेडर स्थानों को दिखाता है आगे और पीछे स्कैनिंग :)

कोड से पहले, मैं अभी भी सुझाव दूंगा कि यदि आप संभवतः फ़ाइल को स्कैन कर सकते हैं और बाद में उपयोग के लिए पैकेट जानकारी की अनुक्रमणिका सहेज सकते हैं तो शायद बेहतर दृष्टिकोण होगा।

PacketHeader.cs:

using System; 

namespace Chapter10Reader 
{ 
    public sealed class PacketHeader 
    { 
     private readonly long filePosition; 
     private readonly ushort channelId; 
     private readonly uint packetLength; 
     private readonly uint dataLength; 
     private readonly byte dataTypeVersion; 
     private readonly byte sequenceNumber; 
     private readonly byte packetFlags; 
     private readonly byte dataType; 
     private readonly ulong relativeTimeCounter; 

     public long FilePosition { get { return filePosition; } } 
     public ushort ChannelId { get { return channelId; } } 
     public uint PacketLength { get { return packetLength; } } 
     public uint DataLength { get { return dataLength; } } 
     public byte DataTypeVersion { get { return dataTypeVersion; } } 
     public byte SequenceNumber { get { return sequenceNumber; } } 
     public byte PacketFlags { get { return packetFlags; } } 
     public byte DataType { get { return dataType; } } 
     public ulong RelativeTimeCounter { get { return relativeTimeCounter; } } 

     public PacketHeader(ushort channelId, uint packetLength, uint dataLength, byte dataTypeVersion, 
      byte sequenceNumber, byte packetFlags, byte dataType, ulong relativeTimeCounter, long filePosition) 
     { 
      this.channelId = channelId; 
      this.packetLength = packetLength; 
      this.dataLength = dataLength; 
      this.dataTypeVersion = dataTypeVersion; 
      this.sequenceNumber = sequenceNumber; 
      this.packetFlags = packetFlags; 
      this.dataType = dataType; 
      this.relativeTimeCounter = relativeTimeCounter; 
      this.filePosition = filePosition; 
     } 

     internal static PacketHeader Parse(byte[] data, int index, long filePosition) 
     { 
      if (index + 24 > data.Length) 
      { 
       throw new ArgumentException("Packet header must be 24 bytes long; not enough data"); 
      } 
      ushort syncPattern = BitConverter.ToUInt16(data, index + 0); 
      if (syncPattern != 0xeb25) 
      { 
       throw new ArgumentException("Packet header must start with the sync pattern"); 
      } 
      ushort channelId = BitConverter.ToUInt16(data, index + 2); 
      uint packetLength = BitConverter.ToUInt32(data, index + 4); 
      uint dataLength = BitConverter.ToUInt32(data, index + 8); 
      byte dataTypeVersion = data[index + 12]; 
      byte sequenceNumber = data[index + 13]; 
      byte packetFlags = data[index + 14]; 
      byte dataType = data[index + 15]; 
      // TODO: Validate this... 
      ulong relativeTimeCounter = 
       (ulong)BitConverter.ToUInt32(data, index + 16) + 
       ((ulong)BitConverter.ToUInt16(data, index + 20)) << 32; 
      // Assume we've already validated the checksum... 
      return new PacketHeader(channelId, packetLength, dataLength, dataTypeVersion, sequenceNumber, 
       packetFlags, dataType, relativeTimeCounter, filePosition); 
     } 

     /// <summary> 
     /// Checks a packet header's checksum to see whether this *looks* like a packet header. 
     /// </summary> 
     internal static bool CheckPacketHeaderChecksum(byte[] data, int index) 
     { 
      if (index + 24 > data.Length) 
      { 
       throw new ArgumentException("Packet header must is 24 bytes long; not enough data"); 
      } 
      ushort computed = 0; 
      for (int i = 0; i < 11; i++) 
      { 
       computed += BitConverter.ToUInt16(data, index + i * 2); 
      } 
      return computed == BitConverter.ToUInt16(data, index + 22); 
     } 
    } 
} 

PacketScanner.cs:

using System; 
using System.Diagnostics; 
using System.IO; 

namespace Chapter10Reader 
{ 
    public sealed class PacketScanner : IDisposable 
    { 
     // 128K buffer... tweak this. 
     private const int BufferSize = 1024 * 128; 

     /// <summary> 
     /// Where in the file does the buffer start? 
     /// </summary> 
     private long bufferStart; 

     /// <summary> 
     /// Where in the file does the buffer end (exclusive)? 
     /// </summary> 
     private long bufferEnd; 

     /// <summary> 
     /// Where are we in the file, logically? 
     /// </summary> 
     private long logicalPosition; 

     // Probably cached by FileStream, but we use it a lot, so let's 
     // not risk it... 
     private readonly long fileLength; 

     private readonly FileStream stream; 
     private readonly byte[] buffer = new byte[BufferSize];   

     private PacketScanner(FileStream stream) 
     { 
      this.stream = stream; 
      this.fileLength = stream.Length; 
     } 

     public void MoveToEnd() 
     { 
      logicalPosition = fileLength; 
      bufferStart = -1; // Invalidate buffer 
      bufferEnd = -1; 
     } 

     public void MoveToBeforeStart() 
     { 
      logicalPosition = -1; 
      bufferStart = -1; 
      bufferEnd = -1; 
     } 

     private byte this[long position] 
     { 
      get 
      { 
       if (position < bufferStart || position >= bufferEnd) 
       { 
        FillBuffer(position); 
       } 
       return buffer[position - bufferStart]; 
      } 
     } 

     /// <summary> 
     /// Fill the buffer to include the given position. 
     /// If the position is earlier than the buffer, assume we're reading backwards 
     /// and make position one before the end of the buffer. 
     /// If the position is later than the buffer, assume we're reading forwards 
     /// and make position the start of the buffer. 
     /// If the buffer is invalid, make position the start of the buffer. 
     /// </summary> 
     private void FillBuffer(long position) 
     { 
      long newStart; 
      if (position > bufferStart) 
      { 
       newStart = position; 
      } 
      else 
      { 
       // Keep position *and position + 1* to avoid swapping back and forth too much 
       newStart = Math.Max(0, position - buffer.Length + 2); 
      } 
      // Make position the start of the buffer. 
      int bytesRead; 
      int index = 0; 
      stream.Position = newStart; 
      while ((bytesRead = stream.Read(buffer, index, buffer.Length - index)) > 0) 
      { 
       index += bytesRead; 
      } 
      bufferStart = newStart; 
      bufferEnd = bufferStart + index; 
     } 

     /// <summary> 
     /// Make sure the buffer contains the given positions. 
     /// 
     /// </summary> 
     private void FillBuffer(long start, long end) 
     { 
      if (end - start > buffer.Length) 
      { 
       throw new ArgumentException("Buffer not big enough!"); 
      } 
      if (end > fileLength) 
      { 
       throw new ArgumentException("Beyond end of file"); 
      } 
      // Nothing to do. 
      if (start >= bufferStart && end < bufferEnd) 
      { 
       return; 
      } 
      // TODO: Optimize this more to use whatever bits we've actually got. 
      // (We're optimized for "we've got the start, get the end" but not the other way round.) 
      if (start >= bufferStart) 
      { 
       // We've got the start, but not the end. Just shift things enough and read the end... 
       int shiftAmount = (int) (end - bufferEnd); 
       Buffer.BlockCopy(buffer, shiftAmount, buffer, 0, (int) (bufferEnd - bufferStart - shiftAmount)); 
       stream.Position = bufferEnd; 
       int bytesRead; 
       int index = (int)(bufferEnd - bufferStart - shiftAmount); 
       while ((bytesRead = stream.Read(buffer, index, buffer.Length - index)) > 0) 
       { 
        index += bytesRead; 
       } 
       bufferStart += shiftAmount; 
       bufferEnd = bufferStart + index; 
       return; 
      } 

      // Just fill the buffer starting from start... 
      bufferStart = -1; 
      bufferEnd = -1; 
      FillBuffer(start); 
     } 

     /// <summary> 
     /// Returns the header of the next packet, or null 
     /// if we've reached the end of the file. 
     /// </summary> 
     public PacketHeader NextHeader() 
     { 
      for (long tryPosition = logicalPosition + 1; tryPosition < fileLength - 23; tryPosition++) 
      { 
       if (this[tryPosition] == 0x25 && this[tryPosition + 1] == 0xEB) 
       { 
        FillBuffer(tryPosition, tryPosition + 24); 
        int bufferPosition = (int) (tryPosition - bufferStart); 
        if (PacketHeader.CheckPacketHeaderChecksum(buffer, bufferPosition)) 
        { 
         logicalPosition = tryPosition; 
         return PacketHeader.Parse(buffer, bufferPosition, tryPosition); 
        } 
       } 
      } 
      logicalPosition = fileLength; 
      return null; 
     } 

     /// <summary> 
     /// Returns the header of the previous packet, or null 
     /// if we've reached the start of the file. 
     /// </summary> 
     public PacketHeader PreviousHeader() 
     { 
      for (long tryPosition = logicalPosition - 1; tryPosition >= 0; tryPosition--) 
      { 
       if (this[tryPosition + 1] == 0xEB && this[tryPosition] == 0x25) 
       { 
        FillBuffer(tryPosition, tryPosition + 24); 
        int bufferPosition = (int)(tryPosition - bufferStart); 
        if (PacketHeader.CheckPacketHeaderChecksum(buffer, bufferPosition)) 
        { 
         logicalPosition = tryPosition; 
         return PacketHeader.Parse(buffer, bufferPosition, tryPosition); 
        } 
       } 
      } 
      logicalPosition = -1; 
      return null; 
     } 

     public static PacketScanner OpenFile(string filename) 
     { 
      return new PacketScanner(File.OpenRead(filename)); 
     } 

     public void Dispose() 
     { 
      stream.Dispose(); 
     } 
    } 
} 

कार्यक्रम

वैसे भी, यहाँ कोड (कोई परीक्षण नमूना कार्यक्रम के अलावा अन्य के साथ पूरा) है (परीक्षण के लिए) .cs:

using System; 
using System.Collections.Generic; 
using System.Linq; 

namespace Chapter10Reader 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string filename = "test.ch10"; 

      Console.WriteLine("Forwards:"); 
      List<long> positionsForward = new List<long>(); 
      using (PacketScanner scanner = PacketScanner.OpenFile(filename)) 
      { 
       scanner.MoveToBeforeStart(); 
       PacketHeader header; 
       while ((header = scanner.NextHeader()) != null) 
       { 
        Console.WriteLine("Found header at {0}", header.FilePosition); 
        positionsForward.Add(header.FilePosition); 
       } 
      } 
      Console.WriteLine(); 
      Console.WriteLine("Backwards:"); 
      List<long> positionsBackward = new List<long>(); 
      using (PacketScanner scanner = PacketScanner.OpenFile(filename)) 
      { 
       scanner.MoveToEnd(); 
       PacketHeader header; 
       while ((header = scanner.PreviousHeader()) != null) 
       { 
        positionsBackward.Add(header.FilePosition); 
       } 
      } 
      positionsBackward.Reverse(); 
      foreach (var position in positionsBackward) 
      { 
       Console.WriteLine("Found header at {0}", position); 
      } 

      Console.WriteLine("Same? {0}", positionsForward.SequenceEqual(positionsBackward)); 
     } 
    } 
} 
+0

एक पैकेट हैडर है जिसमें उसमें एक फ़ील्ड है जो पैकेट के आकार को निर्दिष्ट करता है। मैं पैकेट पढ़ सकता हूं, या मैं अगले पैकेट पर जाने के लिए आकार का उपयोग कर सकता हूं यदि वह पैकेट नहीं है जो मैं चाहता हूं। यह आगे स्कैनिंग के लिए ठीक है, बशर्ते फ़ाइल दूषित न हो, इस स्थिति में मुझे सिंक पैटर्न के लिए स्कैनिंग पर वापस जाना होगा। पैकेट आकार में 1/2 मेगाबाइट तक हो सकते हैं। यदि आप रुचि रखते हैं तो अनुभाग 10.6 से शुरू होने पर पैकेट के लिए विनिर्देश [इस दस्तावेज़] (http://www.irig106.org/docs/106-11/chapter10.pdf) में उत्तेजित विवरण में उपलब्ध है। –

+0

@ रॉबर्ट हार्वे: धन्यवाद, आज रात घर पर एक नज़र डालेंगे और कुछ कोड चाबुक करने का प्रयास करेंगे। क्या आपके पास एक नमूना डेटा फ़ाइल है जिसके साथ मैं खेल सकता हूं? –

+0

UI में अगली/पिछली सुविधा के कारण अनुकूलन आवश्यक है। एक पैकेट द्वारा पीछे की ओर छोड़ना वास्तव में एक समस्या नहीं है; देरी स्वीकार्य है लेकिन गंभीर नहीं है। कई पैकेटों के पीछे पीछे छोड़ना इतना अचूक नहीं है; पैकेट के पास एक चैनल नंबर दिया गया है, और मैं पिछले चैनल * को उसी चैनल में * चाहता हूं, इसलिए मुझे इसे खोजने के लिए सौ पैकेट या अधिक वापस जाना पड़ सकता है। –

संबंधित मुद्दे