Get statistics on completed tasks in C #

I have the following simple code:

var tasks = statements.Select(statement => _session.ExecuteAsync(statement)); var result = Task.WhenAll(tasks).Result; [...] 

How can I calculate min, max, avg, etc. all completed tasks? Task class does not have executeMilliseconds property

+5
source share
2 answers

Using the following extension method:

 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; } 

And callsite

 var tasks = statements.TimedSelect(statement => _session.ExecuteAsync(statement)); var result = Task.WhenAll(tasks).Result; 

You can extract the results you need.

 // 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()); 

Note that this includes the pool timeout (the timeout when the task thread becomes available) and therefore may not be accurate.

Not a general version of this extension is an exercise for the reader.

+3
source

You can set ContinuationTask tasks, which is called what gets called after the task completes. With this, you can use a bunch of stopwatch and use the continuation task to individually stop them.

+2
source

Source: https://habr.com/ru/post/1212803/


All Articles