我正在进行非常简单的测试:
C#:
public static void Test()
{
string fileName = @"c:\Test\big_data.dat";
int NumberOfSeeks = 1000;
int MaxNumberOfBytes = 1;
long fileLength = new FileInfo(fileName).Length;
FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, FileOptions.RandomAccess);
Console.WriteLine("Processing file \"{0}\"", fileName);
Random random = new Random();
DateTime start = DateTime.Now;
byte[] byteArray = new byte[MaxNumberOfBytes];
for (int index = 0; index < NumberOfSeeks; ++index)
{
long offset = (long)(random.NextDouble() * (fileLength - MaxNumberOfBytes - 2));
stream.Seek(offset, SeekOrigin.Begin);
stream.Read(byteArray, 0, MaxNumberOfBytes);
}
Console.WriteLine(
"Total processing time time {0} ms, speed {1} seeks/sec\r\n",
DateTime.Now.Subtract(start).TotalMilliseconds, NumberOfSeeks / (DateTime.Now.Subtract(start).TotalMilliseconds / 1000.0));
stream.Close();
}
然后在 C ++中进行相同的测试:
void test()
{
FILE* file = fopen("c:\\Test\\big_data.dat", "rb");
char buf = 0;
__int64 fileSize = 6216672671;//ftell(file);
__int64 pos;
DWORD dwStart = GetTickCount();
for (int i = 0; i < kTimes; ++i)
{
pos = (rand() % 100) * 0.01 * fileSize;
_fseeki64(file, pos, SEEK_SET);
fread((void*)&buf, 1 , 1,file);
}
DWORD dwEnd = GetTickCount() - dwStart;
printf(" - Raw Reading: %d times reading took %d ticks, e.g %d sec. Speed: %d items/sec\n", kTimes, dwEnd, dwEnd / CLOCKS_PER_SEC, kTimes / (dwEnd / CLOCKS_PER_SEC));
fclose(file);
}
执行时间:
问题:为什么C ++在文件读取这么简单的操作上比C#快数千倍?
其他信息:
答案 0 :(得分:6)
测试的C ++版本存在错误 - 随机偏移的计算受到限制,因此只在短距离内进行搜索,这使得C ++结果看起来更好。
@MooingDuck建议使用正确的偏移计算代码:
<强>兰特()/双(RAND_MAX)*档案大小强>
随着这种变化,C ++和C#的性能变得相当 - 大约200读/秒。
感谢大家的贡献。