5

I have 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. of all executed tasks? The task class doesn't have property like "executedMilliseconds"

4
  • 2
    This isn't the task of a Task. What prevents you to use a Stopwatch, as explained in How long does my code take to run?
    – CodeCaster
    Feb 6, 2015 at 13:04
  • I tried to use Stopwatch, but I don't know how can I measure each task. Feb 6, 2015 at 13:07
  • 1
    So you want to measure each task, not all tasks? Then you'll have to implement a stopwatch in each task.
    – CodeCaster
    Feb 6, 2015 at 13:09
  • Yes exactly I would like to measure EACH task Feb 6, 2015 at 13:25

2 Answers 2

3

With 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 that you'll 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 pool waiting time (time waiting for a task thread to become available), and therefor may not be accurate.

A non-generic variant of this extension is an exercise for the reader.

3
  • Your previous version with Timed method was better, because it allows _session.ExecuteAsync(statement) is not of type of elements in array statement Feb 6, 2015 at 14:00
  • If you change line to function definition to public static IEnumerable<Task<TimedResult<T>>> TimedSelect<X,T>(this IEnumerable<X> source, Func<X, Task<T>> func) it will be better Feb 6, 2015 at 14:02
  • I found TimedSelect better, because the stopwatch starts before the start of the task. The one with Timed chains after the task was started and may lead to incorrect timings. / Edit: updated, thanks.
    – Caramiriel
    Feb 6, 2015 at 14:02
2

You can give tasks a ContinuationTask, which is something that is called after the task has completed. With this you can use a bunch of stopwatches and use the continuation task to individually stop them.

6
  • How can I share stopwatch in base task and ContinuationTask.? Feb 6, 2015 at 13:27
  • To avoid altering the tasks, I would have a Stopwatch[], fire them all off and then stop the nth stopwatch in the nth task. However. SInce Task.WaitAll() makes no guarantees about starting your Tasks in a "fair" way, these metrics would tell you when the tasks finished rather than strictly speaking how long they took to execute. As a general point execution threads are a shared resource so you can't fairly race things concurrently.. Feb 6, 2015 at 13:34
  • You can use a closure over the stopwatch instance for both the pre-task and post-task. However, be careful about unwrapping the inner task, that can get tricky really easily. Continuations are a pain to handle safely.
    – Luaan
    Feb 6, 2015 at 13:54
  • Does ContinuationTasks guarantee that the continuation will start immediately and with the same priority, since it's stated "asynchronously" in MSDN documantation? Anyone? Feb 6, 2015 at 14:11
  • @OğuzSezer So, from riffling through the TaskAwaiter class it would seem it hinges on whether the execution context flows across the await. The class provides an OnCompleted(), where is does flow, and an UnsafeOnCompleted, where it doesn't, for your complier to use. However, I don't know which one the complier would end up using. I feel there are probably no guarantees. Feb 6, 2015 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.