编程语言
首页 > 编程语言> > c#-使用观察值测量响应时间

c#-使用观察值测量响应时间

作者:互联网

给定Observable A代表传入的请求…

interface IRequest
{
  string Id { get; }
}

IObservable<IRequest> requests;

和代表响应的可观察B …

IObservable<string> responses;

我需要测量产生响应所需的时间.我当前的解决方案如下所示.这行得通,但我不确定是否可以简化或更简化.我还担心实际响应时间([GEN])和观察到的响应时间([OBS])之间的偏差,如果将generateResponseTime设置为sub 50ms,该偏差将变得非常小.

class Program
{
    public class Request
    {
        public string Id { get; set; }
    }

    static void Main(string[] args)
    {
        var generatedResponseTime = 100;

        var responseSub = new Subject<string>();

        IObservable<Request> requests = Observable.Interval(TimeSpan.FromMilliseconds(1000))
            .Select(x=> new Request { Id = x.ToString("d") });

        IObservable<string> responses = responseSub.AsObservable();

        var responseTime = requests
            .Where(x => !string.IsNullOrEmpty(x.Id))
            .Select(req => new { Id = req.Id, Start = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() })
            .SelectMany(req => responses
                .Where(reqId => reqId == req.Id)
                .Select(_ => new { RequestId = req.Id, ResponseTime = (int)(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - req.Start) })
                .Take(1))
            .Publish()
            .RefCount();

        requests.ObserveOn(TaskPoolScheduler.Default)
            .Subscribe(req =>
            {
                Console.WriteLine($"[GEN] {req.Id} = {generatedResponseTime} ms");

                Thread.Sleep(generatedResponseTime);
                responseSub.OnNext(req.Id);
            });

        responseTime.Subscribe(x => Console.WriteLine($"[OBS] {x.RequestId} = {x.ResponseTime} ms"));

        Console.ReadLine();
    }
}

解决方法:

这是使用一些内置运算符的替代方法.您的解决方案中也没有多个订阅问题:

var responseTime2 = requests
    .Timestamp()
    .Join(responses.Timestamp(),
        request => Observable.Never<Unit>(), //timeout criteria
        response => Observable.Empty<Unit>(),
        (request, response) => (request: request, response: response)
    )
    .Where(t => t.request.Value.Id == t.response.Value)
    .Select(t => t.response.Timestamp.ToUnixTimeMilliseconds() - t.request.Timestamp.ToUnixTimeMilliseconds())

如果您对请求有任何超时条件,那么从性能的角度来看,将注释放在注释中将很有帮助.否则,Join / Where组合的性能会随着时间的流逝而恶化.

标签:system-reactive,reactive-programming,c
来源: https://codeday.me/bug/20191111/2017750.html