BenchmarkDotNet with async task
Asked Answered
O

1

10

I'm trying to run this code :

public class Parsing
{
    private const string Url ="blabla";
    private static HttpClient client = new HttpClient();

    private static Task<string> newton = ParseNewton();
    private static Task<string> servicestack = ParseServiceStack();

    [Benchmark]
    private static async Task<string> ParseNewton()
    {

        var response = client.GetAsync(Url).Result;

        var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

        var serializer = new Newtonsoft.Json.JsonSerializer();

        using (var sr = new StreamReader(stream))
        using (var jsonTextReader = new JsonTextReader(sr))
        {
            return serializer.Deserialize<string>(jsonTextReader);
        }

    }

    [Benchmark]
    private static async Task<string> ParseServiceStack()
    {

        var response = client.GetAsync(Url).Result;

        var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

        return ServiceStack.Text.JsonSerializer.DeserializeFromStream<string>(stream);

    }
}

And the call is

internal class Program
{
    public static void Main(string[] args)
    {
        var summary = BenchmarkRunner.Run<Parsing>();

        Console.ReadKey();
    }
}

I'm pretty sure I did many things wrong (since it doesn't work) ; I always get the message No Benchmark found and from the samples I found I could not find how to make it work.

I'd like to deserialise like 1000 times the same response from the url given with both NewtonSoft & ServiceStack and get a good benchmark from it. How can I make this code work and what did I do wrong ?

Oersted answered 28/3, 2018 at 14:0 Comment(2)
Does it help if you change the two methods from private to public? The examples I saw also don't use static methods. BenchmarkDotNet will create an instance of the class.Brody
It works... can't believe I lost 30 min on this. Thanks a lot !Oersted
C
9

Both the class and the methods need to be public and can not be static. The class must also not be sealed.

Counterscarp answered 31/1, 2020 at 14:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.