Synchronizacja wydajności odczytu pliku .NET 4.5 z asynchronizacją
Próbujemy zmierzyć wydajność między odczytem serii plików przy użyciu metod synchronizacji a async. Spodziewałem się, że czas między tymi dwoma okresami będzie mniej więcej taki sam, ale okaże się, że async jest o 5,5 razy wolniejszy.
Może to wynikać z kosztów zarządzania wątkami, ale po prostu chciałem poznać Twoją opinię. Może źle mierzymy czasy.
Są to testowane metody:
static void ReadAllFile(string filename)
{
var content = File.ReadAllBytes(filename);
}
static async Task ReadAllFileAsync(string filename)
{
using (var file = File.OpenRead(filename))
{
using (var ms = new MemoryStream())
{
byte[] buff = new byte[file.Length];
await file.ReadAsync(buff, 0, (int)file.Length);
}
}
}
I to jest metoda, która je uruchamia i uruchamia stoper:
static void Test(string name, Func<string, Task> gettask, int count)
{
Stopwatch sw = new Stopwatch();
Task[] tasks = new Task[count];
sw.Start();
for (int i = 0; i < count; i++)
{
string filename = "file" + i + ".bin";
tasks[i] = gettask(filename);
}
Task.WaitAll(tasks);
sw.Stop();
Console.WriteLine(name + " {0} ms", sw.ElapsedMilliseconds);
}
Który z nich jest uruchomiony tutaj:
static void Main(string[] args)
{
int count = 10000;
for (int i = 0; i < count; i++)
{
Write("file" + i + ".bin");
}
Console.WriteLine("Testing read...!");
Test("Read Contents", (filename) => Task.Run(() => ReadAllFile(filename)), count);
Test("Read Contents Async", (filename) => ReadAllFileAsync(filename), count);
Console.ReadKey();
}
I metoda zapisu pomocnika:
static void Write(string filename)
{
Data obj = new Data()
{
Header = "random string size here"
};
int size = 1024 * 20; // 1024 * 256;
obj.Body = new byte[size];
for (var i = 0; i < size; i++)
{
obj.Body[i] = (byte)(i % 256);
}
Stopwatch sw = new Stopwatch();
sw.Start();
MemoryStream ms = new MemoryStream();
Serializer.Serialize(ms, obj);
ms.Position = 0;
using (var file = File.Create(filename))
{
ms.CopyToAsync(file).Wait();
}
sw.Stop();
//Console.WriteLine("Writing file {0}", sw.ElapsedMilliseconds);
}
Wyniki:
-Read Contents 574 ms
-Read Contents Async 3160 ms
Naprawdę docenisz, jeśli ktoś może rzucić trochę światła na to, jak przeszukaliśmy stos i sieć, ale nie możemy znaleźć właściwego wyjaśnienia.