Stiamo provando a misurare le prestazioni tra la lettura di una serie di file utilizzando i metodi di sincronizzazione vs async. Mi aspettavo di avere circa lo stesso tempo tra i due ma risulta che usando async è circa 5,5 volte più lento.C# 4.5 file read sync performance async
Questo potrebbe essere dovuto al sovraccarico di gestione dei thread ma volevo solo sapere la tua opinione. Forse stiamo solo misurando i tempi sbagliati.
Questi sono i metodi in fase di sperimentazione:
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);
}
}
}
e questo è il metodo che li gestisce e avvia il cronometro:
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);
}
che è tutto eseguito da qui:
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();
}
E il metodo di scrittura dell'helper:
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);
}
I risultati:
-Read Contents 574 ms
-Read Contents Async 3160 ms
sarà davvero apprezzare se qualcuno può far luce su questo come abbiamo cercato la pila e il web, ma non può davvero trovare una spiegazione adeguata.
Il test potrebbe essere difettoso mentre si generano thread per eseguire contemporaneamente le letture. Un test migliore sarebbe testare su cosa e poi testare l'altro. – Kami
Su una nota diversa, c'è un metodo statico elegante su Stopwatch chiamato 'StartNew', fondamentalmente fa' var s = new Stopwatch(); s.Start(); return s; 'quindi non devi. :-) – Patrick
Penso che quel test sia difettoso. Hai misurato la differenza tra ReadAllBytes e Read?Questa potrebbe essere la prima cosa, che ReadAllBytes è più efficiente - forse è un'operazione "atomica"? – TGlatzer