|
| 1 | +using System; |
| 2 | +using System.Diagnostics; |
| 3 | +using System.IO; |
| 4 | +using System.Threading.Tasks; |
| 5 | +using Microsoft.AspNetCore.NodeServices; |
| 6 | + |
| 7 | +namespace ConsoleApplication |
| 8 | +{ |
| 9 | + // This project is a micro-benchmark for .NET->Node RPC via NodeServices. It doesn't reflect |
| 10 | + // real-world usage patterns (you're not likely to make hundreds of sequential calls like this), |
| 11 | + // but is a starting point for comparing the overhead of different hosting models and transports. |
| 12 | + public class Program |
| 13 | + { |
| 14 | + public static void Main(string[] args) { |
| 15 | + using (var nodeServices = CreateNodeServices(NodeHostingModel.Http)) { |
| 16 | + MeasureLatency(nodeServices).Wait(); |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + private static async Task MeasureLatency(INodeServices nodeServices) { |
| 21 | + // Ensure the connection is open, so we can measure per-request timings below |
| 22 | + var response = await nodeServices.Invoke<string>("latencyTest", "C#"); |
| 23 | + Console.WriteLine(response); |
| 24 | + |
| 25 | + // Now perform a series of requests, capturing the time taken |
| 26 | + const int requestCount = 100; |
| 27 | + var watch = Stopwatch.StartNew(); |
| 28 | + for (var i = 0; i < requestCount; i++) { |
| 29 | + await nodeServices.Invoke<string>("latencyTest", "C#"); |
| 30 | + } |
| 31 | + |
| 32 | + // Display results |
| 33 | + var elapsedSeconds = (float)watch.ElapsedTicks / Stopwatch.Frequency; |
| 34 | + Console.WriteLine("\nTotal time: {0:F2} milliseconds", 1000 * elapsedSeconds); |
| 35 | + Console.WriteLine("\nTime per invocation: {0:F2} milliseconds", 1000 * elapsedSeconds / requestCount); |
| 36 | + } |
| 37 | + |
| 38 | + private static INodeServices CreateNodeServices(NodeHostingModel hostingModel) { |
| 39 | + return Configuration.CreateNodeServices(new NodeServicesOptions { |
| 40 | + HostingModel = hostingModel, |
| 41 | + ProjectPath = Directory.GetCurrentDirectory(), |
| 42 | + WatchFileExtensions = new string[] {} // Don't watch anything |
| 43 | + }); |
| 44 | + } |
| 45 | + } |
| 46 | +} |
0 commit comments