0

我正在尝试制作一个文件比较程序,我想要实现的功能之一是计算所选择的两个文件的相似性和差异性。我希望这种比较在大文件上快速(如果可能的话)。我不确定应该使用什么方法,但最后我想要一个百分比。

请参阅此 gif以获得视觉想法。

4

2 回答 2

0

您可能想要类似于二进制差异实用程序所见的相似性——而不是愚蠢的逐字节比较。但是,嘿,只是为了好玩...

unsafe static long DumbDifference(string file1Path, string file2Path)
{
    // completely untested! also, add some using()s here.
    // also, map views in chunks if you plan to use it on large files.

    MemoryMappedFile file1 = MemoryMappedFile.CreateFromFile(
             file1Path, System.IO.FileMode.Open,
             null, 0, MemoryMappedFileAccess.Read);
    MemoryMappedFile file2 = MemoryMappedFile.CreateFromFile(
             file2Path, System.IO.FileMode.Open,
             null, 0, MemoryMappedFileAccess.Read);
    MemoryMappedViewAccessor view1 = file1.CreateViewAccessor();
    MemoryMappedViewAccessor view2 = file2.CreateViewAccessor();

    long length1 = checked((long)view1.SafeMemoryMappedViewHandle.ByteLength);
    long length2 = checked((long)view2.SafeMemoryMappedViewHandle.ByteLength);
    long minLength = Math.Min(length1, length2);

    byte* ptr1 = null, ptr2 = null;
    view1.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr1);
    view2.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr2);

    ulong differences = (ulong)Math.Abs(length1 - length2);

    for (long i = 0; i < minLength; ++i)
    {
        // if you expect your files to be pretty similar,
        // you could optimize this by comparing long-sized chunks.
        differences += ptr1[i] != ptr2[i] ? 1u : 0u;
    }

    return checked((long)differences);
}

太糟糕了 .NET 没有内置的 SIMD 支持。

于 2013-10-05T01:30:01.687 回答
0

如果你可以使用 linq 这应该没问题。

var results = your1stEnumerable.Intersect(your2ndEnumerable);
于 2013-10-05T01:58:32.417 回答