Con il seguente metodo di estensione:
public static class EnumerableExtensions
{
public static IEnumerable<Task<TimedResult<TReturn>>> TimedSelect<TSource, TReturn>(
this IEnumerable<TSource> source,
Func<TSource, Task<TReturn>> func)
{
if (source == null) throw new ArgumentNullException("source");
if (func == null) throw new ArgumentNullException("func");
return source.Select(x =>
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Task<TReturn> task = func(x);
Task<TimedResult<TReturn>> timedResultTask = task
.ContinueWith(y =>
{
stopwatch.Stop();
return new TimedResult<TReturn>(task, stopwatch.Elapsed);
});
return timedResultTask;
});
}
}
public class TimedResult<T>
{
internal TimedResult(Task<T> task, TimeSpan duration)
{
Task = task;
Duration = duration;
}
public readonly Task<T> Task;
public readonly TimeSpan Duration;
}
E callsite
var tasks = statements.TimedSelect(statement => _session.ExecuteAsync(statement));
var result = Task.WhenAll(tasks).Result;
È possibile estrarre i risultati che avrete bisogno
// Whatever works (ugly, but just as an example)...
var min = result.Select(x => x.Duration).Min();
var max = result.Select(x => x.Duration).Max();
var avg = new TimeSpan((long)result.Select(x => x.Duration.Ticks).Average());
Si noti che questo include piscina tempo di attesa (tempo in attesa che un thread di attività diventi disponibile) e quindi potrebbe non essere accurato.
Una variante non generica di questa estensione è un esercizio per il lettore.
Questo non è il compito di un'attività. Cosa ti impedisce di usare un cronometro, come spiegato in [Quanto tempo impiega il mio codice per funzionare?] (Http://stackoverflow.com/questions/1285052/how-long-does-my-code-take-to-run – CodeCaster
Ho provato ad usare il cronometro, ma non so come posso misurare ogni attività. –
Quindi vuoi misurare _each_ task, non _all_ tasks? Quindi dovrai implementare un cronometro in ogni attività. – CodeCaster