2012-10-15 27 views
7

我正在使用的一些代碼偶爾需要引用長UNC路徑(例如\\?\ UNC \ MachineName \ Path),但我們發現無論如何即使在同一臺計算機上,目錄所在的位置通過UNC路徑訪問時比本地路徑慢得多。指向本地目錄的UNC路徑比本地訪問慢得多

例如,我們編寫了一些基準代碼,將一串亂碼寫入文件,然後多次讀回。

  • C::\ TEMP
  • \\計算機的\ Temp
  • 我有6點不同的方式來訪問相同的共享目錄我的開發機器上,在同一臺機器上運行的代碼,測試它\\?\ C:?\溫度
  • \\。\ UNC \計算機名\溫度
  • \\ 127.0.0.1的\ Temp
  • \\。\ UNC \ 127.0.0.1的\ Temp

這裏是結果:

Testing: C:\Temp 
Wrote 1000 files to C:\Temp in 861.0647 ms 
Read 1000 files from C:\Temp in 60.0744 ms 
Testing: \\MachineName\Temp 
Wrote 1000 files to \\MachineName\Temp in 2270.2051 ms 
Read 1000 files from \\MachineName\Temp in 1655.0815 ms 
Testing: \\?\C:\Temp 
Wrote 1000 files to \\?\C:\Temp in 916.0596 ms 
Read 1000 files from \\?\C:\Temp in 60.0517 ms 
Testing: \\?\UNC\MachineName\Temp 
Wrote 1000 files to \\?\UNC\MachineName\Temp in 2499.3235 ms 
Read 1000 files from \\?\UNC\MachineName\Temp in 1684.2291 ms 
Testing: \\127.0.0.1\Temp 
Wrote 1000 files to \\127.0.0.1\Temp in 2516.2847 ms 
Read 1000 files from \\127.0.0.1\Temp in 1721.1925 ms 
Testing: \\?\UNC\127.0.0.1\Temp 
Wrote 1000 files to \\?\UNC\127.0.0.1\Temp in 2499.3211 ms 
Read 1000 files from \\?\UNC\127.0.0.1\Temp in 1678.18 ms 

我試過IP地址來排除DNS問題。它可以檢查每個文件訪問權限嗎?如果是這樣,有沒有辦法緩存它?它是否僅僅假設它是UNC路徑,它應該通過TCP/IP完成所有操作,而不是直接訪問磁盤?我們用於讀/寫的代碼有問題嗎?我已經刪除了相關的基準測試部分,如下所示:

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Runtime.InteropServices; 
using System.Text; 
using Microsoft.Win32.SafeHandles; 
using Util.FileSystem; 

namespace UNCWriteTest { 
    internal class Program { 
     [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
     public static extern bool DeleteFile(string path); // File.Delete doesn't handle \\?\UNC\ paths 

     private const int N = 1000; 

     private const string TextToSerialize = 
      "asd;lgviajsmfopajwf0923p84jtmpq93worjgfq0394jktp9orgjawefuogahejngfmliqwegfnailsjdhfmasodfhnasjldgifvsdkuhjsmdofasldhjfasolfgiasngouahfmp9284jfqp92384fhjwp90c8jkp04jk34pofj4eo9aWIUEgjaoswdfg8jmp409c8jmwoeifulhnjq34lotgfhnq34g"; 

     private static readonly byte[] _Buffer = Encoding.UTF8.GetBytes(TextToSerialize); 

     public static string WriteFile(string basedir) { 
      string fileName = Path.Combine(basedir, string.Format("{0}.tmp", Guid.NewGuid())); 

      try { 
       IntPtr writeHandle = NativeFileHandler.CreateFile(
        fileName, 
        NativeFileHandler.EFileAccess.GenericWrite, 
        NativeFileHandler.EFileShare.None, 
        IntPtr.Zero, 
        NativeFileHandler.ECreationDisposition.New, 
        NativeFileHandler.EFileAttributes.Normal, 
        IntPtr.Zero); 

       // if file was locked 
       int fileError = Marshal.GetLastWin32Error(); 
       if ((fileError == 32 /* ERROR_SHARING_VIOLATION */) || (fileError == 80 /* ERROR_FILE_EXISTS */)) { 
        throw new Exception("oopsy"); 
       } 

       using (var h = new SafeFileHandle(writeHandle, true)) { 
        using (var fs = new FileStream(h, FileAccess.Write, NativeFileHandler.DiskPageSize)) { 
         fs.Write(_Buffer, 0, _Buffer.Length); 
        } 
       } 
      } 
      catch (IOException) { 
       throw; 
      } 
      catch (Exception ex) { 
       throw new InvalidOperationException(" code " + Marshal.GetLastWin32Error(), ex); 
      } 

      return fileName; 
     } 

     public static void ReadFile(string fileName) { 
      var fileHandle = 
       new SafeFileHandle(
        NativeFileHandler.CreateFile(fileName, NativeFileHandler.EFileAccess.GenericRead, NativeFileHandler.EFileShare.Read, IntPtr.Zero, 
               NativeFileHandler.ECreationDisposition.OpenExisting, NativeFileHandler.EFileAttributes.Normal, IntPtr.Zero), true); 

      using (fileHandle) { 
       //check the handle here to get a bit cleaner exception semantics 
       if (fileHandle.IsInvalid) { 
        //ms-help://MS.MSSDK.1033/MS.WinSDK.1033/debug/base/system_error_codes__0-499_.htm 
        int errorCode = Marshal.GetLastWin32Error(); 
        //now that we've taken more than our allotted share of time, throw the exception 
        throw new IOException(string.Format("file read failed on {0} to {1} with error code {1}", fileName, errorCode)); 
       } 

       //we have a valid handle and can actually read a stream, exceptions from serialization bubble out 
       using (var fs = new FileStream(fileHandle, FileAccess.Read, 1*NativeFileHandler.DiskPageSize)) { 
        //if serialization fails, we'll just let the normal serialization exception flow out 
        var foo = new byte[256]; 
        fs.Read(foo, 0, 256); 
       } 
      } 
     } 

     public static string[] TestWrites(string baseDir) { 
      try { 
       var fileNames = new List<string>(); 
       DateTime start = DateTime.UtcNow; 
       for (int i = 0; i < N; i++) { 
        fileNames.Add(WriteFile(baseDir)); 
       } 
       DateTime end = DateTime.UtcNow; 

       Console.Out.WriteLine("Wrote {0} files to {1} in {2} ms", N, baseDir, end.Subtract(start).TotalMilliseconds); 
       return fileNames.ToArray(); 
      } 
      catch (Exception e) { 
       Console.Out.WriteLine("Failed to write for " + baseDir + " Exception: " + e.Message); 
       return new string[] {}; 
      } 
     } 

     public static void TestReads(string baseDir, string[] fileNames) { 
      try { 
       DateTime start = DateTime.UtcNow; 

       for (int i = 0; i < N; i++) { 
        ReadFile(fileNames[i%fileNames.Length]); 
       } 
       DateTime end = DateTime.UtcNow; 

       Console.Out.WriteLine("Read {0} files from {1} in {2} ms", N, baseDir, end.Subtract(start).TotalMilliseconds); 
      } 
      catch (Exception e) { 
       Console.Out.WriteLine("Failed to read for " + baseDir + " Exception: " + e.Message); 
      } 
     } 

     private static void Main(string[] args) { 
      foreach (string baseDir in args) { 
       Console.Out.WriteLine("Testing: {0}", baseDir); 

       string[] fileNames = TestWrites(baseDir); 

       TestReads(baseDir, fileNames); 

       foreach (string fileName in fileNames) { 
        DeleteFile(fileName); 
       } 
      } 
     } 
    } 
} 

回答

6

這並不讓我感到意外。您正在寫入/讀取相當少量的數據,因此文件系統緩存可能會最大限度地減少物理磁盤I/O的影響;基本上,瓶頸將成爲CPU。我不確定流量是否將通過TCP/IP協議棧進行傳輸,但至少涉及SMB協議。一方面,這意味着請求將在SMB客戶端進程和SMB服務器進程之間來回傳遞,因此您可以在三個不同的進程(包括您自己的進程)之間切換上下文。使用本地文件系統路徑切換到內核模式並返回,但不涉及其他進程。上下文切換是比從內核模式轉換和從內核模式轉換更慢

可能會有兩個不同的額外開銷,每個文件一個,每千字節一個數據。在這個特定的測試中,每文件SMB開銷可能占主導地位。因爲涉及的數據量也會影響物理磁盤I/O的影響,所以在處理大量小文件時,這可能只是一個問題。