public override async Task ProcessAsync(ArraySegment <byte> data) { Stopwatch stopwatch = Stopwatch.StartNew(); IncrementBytesReceivedMetric(data.Count); using TextReader request = new StreamReader(new MemoryStream(data.Array !, data.Offset, data.Count), Encoding.UTF8); int allResponsesSize = 0; await foreach (JsonRpcResult result in _jsonRpcProcessor.ProcessAsync(request, _jsonRpcContext)) { using (result) { int singleResponseSize = await SendJsonRpcResult(result); allResponsesSize += singleResponseSize; if (result.IsCollection) { _jsonRpcLocalStats.ReportCalls(result.Reports); long handlingTimeMicroseconds = stopwatch.ElapsedMicroseconds(); _jsonRpcLocalStats.ReportCall(new RpcReport("# collection serialization #", handlingTimeMicroseconds, true), handlingTimeMicroseconds, singleResponseSize); stopwatch.Restart(); } else { long handlingTimeMicroseconds = stopwatch.ElapsedMicroseconds(); _jsonRpcLocalStats.ReportCall(result.Report, handlingTimeMicroseconds, singleResponseSize); stopwatch.Restart(); } } } IncrementBytesSentMetric(allResponsesSize); }
/// <summary> /// Prints the elapsed time using the most appropriate unit. /// </summary> /// <param name="stopwatch">The stopwatch object.</param> /// <returns>The string with printed value.</returns> public static string Print(this Stopwatch stopwatch) { if (stopwatch == null) { throw new ArgumentNullException(nameof(stopwatch)); } if (stopwatch.ElapsedMilliseconds > 1000) { return($"{(double)stopwatch.ElapsedMilliseconds / 1000:N} sec"); } else if (stopwatch.ElapsedMicroseconds() > 1000) { return($"{(double)stopwatch.ElapsedMicroseconds() / 1000:N} msec"); } else { return($"{stopwatch.ElapsedMicroseconds():N} μsec"); } }
public static void DelayMicroSeconds(int ms) { var sw = new Stopwatch(); sw.Start(); while (sw.ElapsedMicroseconds() < ms) { continue; } }
public Task <(long totalMicroseconds, (long initialMicroseconds, int[] segments)[] results)> Run() { Stopwatch sw = new Stopwatch(); var tasks = Enumerable.Range(0, ThreadsCount).Select(x => new Task <(long initialMicroseconds, int[] segments)>(() => { var segments = new List <int>(MaxMeaturementsPerThreadCount); //should be recorded right before meaturement loop var initialMicroseconds = sw.ElapsedMicroseconds(); var prevMicroseconds = initialMicroseconds; while (sw.ElapsedMicroseconds() - initialMicroseconds < ObservationTimePerThreadMicroseconds) { //delay while (sw.ElapsedMicroseconds() - prevMicroseconds < GranularityMicroseconds) { } var currentMicroseconds = sw.ElapsedMicroseconds(); segments.Add((int)(currentMicroseconds - prevMicroseconds)); prevMicroseconds = currentMicroseconds; } return(initialMicroseconds, segments.ToArray()); })).ToArray(); //should be launched right before start of the tasks sw.Start(); foreach (var task in tasks) { task.Start(); } return(Task.WhenAll(tasks).ContinueWith(x => { sw.Stop(); return (sw.ElapsedMicroseconds(), x.Result); })); }
public void Play(Dictionary <long, List <KeyEvent> > keyPlaybackBuffer, int interludeDelay) { if (!Playing) { KeyPlayingTask = Task.Run( async() => { var currentTimestamp = 0L; var keyInputSequences = KeyInputSequencer.BuildSequence(keyPlaybackBuffer); var enumerator = keyInputSequences.GetEnumerator(); SW = new Stopwatch(); SW.Start(); while (enumerator.MoveNext()) { try { await Task.Delay(interludeDelay).ConfigureAwait(false); currentTimestamp = SW.ElapsedMicroseconds(); var err = HouseofCat.Windows.NativeMethods.SendInput( (uint)enumerator.Current.InputSequence.Length, enumerator.Current.InputSequence, Marshal.SizeOf(typeof(INPUT))); if (err > 1) { await KeyEventMessageChannelWriter .WriteAsync(string.Format(SendInputError, err)); } else { await KeyEventMessageChannelWriter .WriteAsync( string.Format(KeySequenceInputLog, enumerator.Current.KeySequence, currentTimestamp)); } } catch (Exception ex) { await KeyEventMessageChannelWriter .WriteAsync( string.Format(UknownError, ex.Message, ex.StackTrace)); } } Playing = false; }); } }
public static void WaitMicroseconds(int microseconds) { Stopwatch stopwatch = Stopwatch.StartNew(); lock (SyncRoot) { while (true) { if (stopwatch.ElapsedMicroseconds() >= microseconds) { break; } } } }
private IntPtr KeyboardProc(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode >= 0) { var time = SW.ElapsedMicroseconds(); var key = (Keys)Marshal.ReadInt32(lParam); var action = wParam.ToInt32(); (var actionString, var flag) = NativeMethods.GetActivityFlags(action); // Send to buffer for Async writes to UI. KeyChannelWriter.TryWrite(string.Format(KeyEventTemplate, key, actionString, time)); // Allows multiple keypresses on the same frame time. if (KeyPlaybackBuffer.ContainsKey(time)) { KeyPlaybackBuffer[time].Add( new KeyEvent { Action = action, ActionString = actionString, Flag = flag, Timestamp = time, Key = key, KeyIntPtr = lParam }); } else { KeyPlaybackBuffer[time] = new List <KeyEvent> { new KeyEvent { Action = action, ActionString = actionString, Flag = flag, Timestamp = time, Key = key, KeyIntPtr = lParam } }; } } return(NativeMethods.CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam)); }
public async Task ReceiveAsync(Memory <byte> data) { Stopwatch stopwatch = Stopwatch.StartNew(); using JsonRpcResult result = await _jsonRpcProcessor.ProcessAsync(Encoding.UTF8.GetString(data.Span), _jsonRpcContext); await SendJsonRpcResult(result); if (result.IsCollection) { _jsonRpcLocalStats.ReportCalls(result.Reports); _jsonRpcLocalStats.ReportCall(new RpcReport("# collection serialization #", stopwatch.ElapsedMicroseconds(), true)); } else { _jsonRpcLocalStats.ReportCall(result.Report, stopwatch.ElapsedMicroseconds()); } }
public async Task ReceiveAsync(Memory <byte> data) { string SerializeTimeoutException() { JsonRpcErrorResponse error = _jsonRpcService.GetErrorResponse(ErrorCodes.Timeout, "Request was canceled due to enabled timeout."); return(_jsonSerializer.Serialize(error)); } Stopwatch stopwatch = Stopwatch.StartNew(); using JsonRpcResult result = await _jsonRpcProcessor.ProcessAsync(Encoding.UTF8.GetString(data.ToArray())); string resultData; try { resultData = result.IsCollection ? _jsonSerializer.Serialize(result.Responses) : _jsonSerializer.Serialize(result.Response); } catch (Exception e) when(e.InnerException is OperationCanceledException) { resultData = SerializeTimeoutException(); } catch (OperationCanceledException) { resultData = SerializeTimeoutException(); } await SendRawAsync(resultData); if (result.IsCollection) { _jsonRpcLocalStats.ReportCalls(result.Reports); _jsonRpcLocalStats.ReportCall(new RpcReport("# collection serialization #", stopwatch.ElapsedMicroseconds(), true)); } else { _jsonRpcLocalStats.ReportCall(result.Report, stopwatch.ElapsedMicroseconds()); } }
static void Measure <T>(string text, bool warmup, Func <T> func) { if (warmup) { Console.WriteLine($"Warming up... "); func.Invoke(); return; } Console.Write($"Measuring... "); sw_.Restart(); T r = func.Invoke(); float elapsedMicroseconds = sw_.ElapsedMicroseconds(); if (!results_.ContainsKey(text)) { results_[text] = new List <float>(); } results_[text].Add(elapsedMicroseconds); Console.WriteLine($"it took {elapsedMicroseconds.ToString("f0").PadLeft(5)} µs to {text}. Result: {r}"); }
public async Task ReceiveAsync(Memory <byte> data) { Stopwatch stopwatch = Stopwatch.StartNew(); Interlocked.Add(ref Metrics.JsonRpcBytesReceivedWebSockets, data.Length); using JsonRpcResult result = await _jsonRpcProcessor.ProcessAsync(Encoding.UTF8.GetString(data.Span), _jsonRpcContext); var size = await SendJsonRpcResult(result); long handlingTimeMicroseconds = stopwatch.ElapsedMicroseconds(); if (result.IsCollection) { _jsonRpcLocalStats.ReportCalls(result.Reports); _jsonRpcLocalStats.ReportCall(new RpcReport("# collection serialization #", handlingTimeMicroseconds, true), handlingTimeMicroseconds, size); } else { _jsonRpcLocalStats.ReportCall(result.Report, handlingTimeMicroseconds, size); } Interlocked.Add(ref Metrics.JsonRpcBytesSentWebSockets, data.Length); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IJsonRpcProcessor jsonRpcProcessor, IJsonRpcService jsonRpcService, IJsonRpcLocalStats jsonRpcLocalStats) { void SerializeTimeoutException(IJsonRpcService service, Stream resultStream) { JsonRpcErrorResponse?error = service.GetErrorResponse(ErrorCodes.Timeout, "Request was canceled due to enabled timeout."); _jsonSerializer.Serialize(resultStream, error); } _jsonSerializer = CreateJsonSerializer(); foreach (JsonConverter converter in jsonRpcService.Converters) { _jsonSerializer.RegisterConverter(converter); } if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors("Cors"); IConfigProvider configProvider = app.ApplicationServices.GetService <IConfigProvider>(); IInitConfig initConfig = configProvider.GetConfig <IInitConfig>(); IJsonRpcConfig jsonRpcConfig = configProvider.GetConfig <IJsonRpcConfig>(); if (initConfig.WebSocketsEnabled) { app.UseWebSockets(); app.UseWhen(ctx => ctx.WebSockets.IsWebSocketRequest && ctx.Connection.LocalPort == jsonRpcConfig.WebSocketsPort, builder => builder.UseWebSocketsModules()); } app.Use(async(ctx, next) => { if (ctx.Request.Method == "GET") { await ctx.Response.WriteAsync("Nethermind JSON RPC"); } else if (ctx.Connection.LocalPort == jsonRpcConfig.Port && ctx.Request.Method == "POST") { Stopwatch stopwatch = Stopwatch.StartNew(); using StreamReader reader = new StreamReader(ctx.Request.Body, Encoding.UTF8); string request = await reader.ReadToEndAsync(); using JsonRpcResult result = await jsonRpcProcessor.ProcessAsync(request); ctx.Response.ContentType = "application/json"; Stream resultStream = jsonRpcConfig.BufferResponses ? new MemoryStream() : ctx.Response.Body; try { if (result.IsCollection) { _jsonSerializer.Serialize(resultStream, result.Responses); } else { _jsonSerializer.Serialize(resultStream, result.Response); } if (jsonRpcConfig.BufferResponses) { ctx.Response.ContentLength = resultStream.Length; resultStream.Seek(0, SeekOrigin.Begin); await resultStream.CopyToAsync(ctx.Response.Body); } } catch (Exception e) when(e.InnerException is OperationCanceledException) { SerializeTimeoutException(jsonRpcService, resultStream); } catch (OperationCanceledException) { SerializeTimeoutException(jsonRpcService, resultStream); } finally { await ctx.Response.CompleteAsync(); if (jsonRpcConfig.BufferResponses) { await resultStream.DisposeAsync(); } } if (result.IsCollection) { jsonRpcLocalStats.ReportCalls(result.Reports); jsonRpcLocalStats.ReportCall(new RpcReport("# collection serialization #", stopwatch.ElapsedMicroseconds(), true)); } else { jsonRpcLocalStats.ReportCall(result.Report, stopwatch.ElapsedMicroseconds()); } } }); }
static void Main(string[] args) { Parser.Default.ParseArguments <Options>(args) .WithParsed <Options>(o => { int port = 0x9998; string raft_ip = "224.255.255.255"; UdpClient client = new UdpClient(); client.Connect(raft_ip, port); // Preparazione pacchetto byte[] source = new byte[] { 0x00, // 1Byte type_sourceID; 0x00, // 1Byte length_sourceID; }.Concat(BitConverter.GetBytes(o.SourceId)).ToArray(); // 2Bytes sourceID; // ID of the source Node byte[] destination = new byte[] { 0x00, // 1Byte type_destinationID; 0x00, // 1Byte length_destinationID; }.Concat(BitConverter.GetBytes(o.DestinationId)).ToArray(); // 2Bytes destinationID; // ID of the destination Node byte[] logindex = { 0x00, // 1Byte type_logIndex; 0x00, // 1Byte length_logIndex; 0x00, 0x00, 0x00, 0x00 // 4Bytes logIndex; // index of the last entry on Leader's log }; byte[] currentTerm = { 0x00, // 1Byte type_currentTerm; 0x00, // 1Byte length_currentTerm; 0x00, 0x00, 0x00, 0x01, // 4Bytes currentTerm; // or Epoch }; byte[] data = { 0x00, // 1Byte type_data; 0x00, // 1Byte length_data; 0x00, 0x00, 0x00, 0x00, // actual value to be pushed inside the log 0x00, 0x00, 0x00, 0x00, // actual value to be pushed inside the log }; byte[] messageType = new byte[] { 0x00, // 1Byte type_messageType; 0x00, // 1Byte length_messageType; o.MessageType // 1Byte messageType; // represents the command }; byte[] version = { 0x00 // 1Byte version; // protocol version }; Stopwatch sw = new Stopwatch(); Stopwatch innerSw = new Stopwatch(); innerSw.Start(); sw.Start(); var waitMs = (int)((1f / o.PacketsPerSecond) * 1000); var waitMicro = (int)((1f / o.PacketsPerSecond) * 1000000); long counter = 0; while (o.PacketCount == 0 || counter < o.PacketCount) { byte[] buffer = new byte[34]; Buffer.BlockCopy(source, 0, buffer, 0, 4); Buffer.BlockCopy(destination, 0, buffer, 4, 4); Buffer.BlockCopy(logindex, 0, buffer, 8, 6); Buffer.BlockCopy(currentTerm, 0, buffer, 14, 6); Buffer.BlockCopy(new byte[] { 0x00, 0x00 }, 0, buffer, 20, 2); // Type e Length del data Buffer.BlockCopy(BitConverter.GetBytes(counter), 0, buffer, 22, 8); // Data to push inside log Buffer.BlockCopy(messageType, 0, buffer, 30, 3); Buffer.BlockCopy(version, 0, buffer, 33, 1); client.Send(buffer, buffer.Length); counter++; if (o.PacketsPerSecond <= 1000) { Thread.Sleep(waitMs); } else { var start = innerSw.ElapsedMicroseconds(); double ms = 0; do { ms = innerSw.ElapsedMicroseconds(); }while (waitMicro > (ms - start)); } } sw.Stop(); innerSw.Stop(); Console.WriteLine($"Secondi trascorsi: {sw.Elapsed.TotalSeconds}"); }); }
public void is_copy_slower_for_big_arrays() { var gen2Gc = GC.CollectionCount(2); var smallArray = new ArraySegment<byte>[1024]; var bigArray = new ArraySegment<byte>[1024*64]; var destinationArray = new ArraySegment<byte>[512]; //warmup var batchSize = 100000; for (int i = 0; i < batchSize; i++) { Array.Copy(smallArray, 512, destinationArray, 0, 512); Array.Copy(bigArray, 512, destinationArray, 0, 512); } var watch = new Stopwatch(); watch.Start(); for (int i = 0; i < batchSize; i++) { Array.Copy(smallArray,512,destinationArray,0,512); } watch.Stop(); Console.WriteLine(string.Format("small copy us {0}", watch.ElapsedMicroseconds()) ); watch = new Stopwatch(); watch.Start(); for (int i = 0; i < batchSize; i++) { Array.Copy(bigArray, 2048, destinationArray, 0, 512); } watch.Stop(); Console.WriteLine(string.Format("big copy us {0}", watch.ElapsedMicroseconds())); gen2Gc = GC.CollectionCount(2) - gen2Gc; Console.WriteLine(gen2Gc); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IJsonRpcProcessor jsonRpcProcessor, IJsonRpcService jsonRpcService, IJsonRpcLocalStats jsonRpcLocalStats, IJsonSerializer jsonSerializer) { long SerializeTimeoutException(IJsonRpcService service, Stream resultStream) { JsonRpcErrorResponse?error = service.GetErrorResponse(ErrorCodes.Timeout, "Request was canceled due to enabled timeout."); return(jsonSerializer.Serialize(resultStream, error)); } if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors("Cors"); app.UseRouting(); app.UseResponseCompression(); IConfigProvider? configProvider = app.ApplicationServices.GetService <IConfigProvider>(); IRpcAuthentication?rpcAuthentication = app.ApplicationServices.GetService <IRpcAuthentication>(); if (configProvider == null) { throw new ApplicationException($"{nameof(IConfigProvider)} has not been loaded properly"); } ILogManager? logManager = app.ApplicationServices.GetService <ILogManager>() ?? NullLogManager.Instance; ILogger logger = logManager.GetClassLogger(); IInitConfig initConfig = configProvider.GetConfig <IInitConfig>(); IJsonRpcConfig jsonRpcConfig = configProvider.GetConfig <IJsonRpcConfig>(); IJsonRpcUrlCollection jsonRpcUrlCollection = app.ApplicationServices.GetRequiredService <IJsonRpcUrlCollection>(); IHealthChecksConfig healthChecksConfig = configProvider.GetConfig <IHealthChecksConfig>(); if (initConfig.WebSocketsEnabled) { app.UseWebSockets(new WebSocketOptions()); app.UseWhen(ctx => ctx.WebSockets.IsWebSocketRequest && jsonRpcUrlCollection.TryGetValue(ctx.Connection.LocalPort, out JsonRpcUrl jsonRpcUrl) && jsonRpcUrl.RpcEndpoint.HasFlag(RpcEndpoint.Ws), builder => builder.UseWebSocketsModules()); } app.UseEndpoints(endpoints => { if (healthChecksConfig.Enabled) { try { endpoints.MapHealthChecks(healthChecksConfig.Slug, new HealthCheckOptions() { Predicate = _ => true, ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse }); if (healthChecksConfig.UIEnabled) { endpoints.MapHealthChecksUI(setup => setup.AddCustomStylesheet(Path.Combine(AppDomain.CurrentDomain.BaseDirectory !, "nethermind.css"))); } } catch (Exception e) { if (logger.IsError) { logger.Error("Unable to initialize health checks. Check if you have Nethermind.HealthChecks.dll in your plugins folder.", e); } } } }); app.Run(async(ctx) => { if (ctx.Request.Method == "GET") { await ctx.Response.WriteAsync("Nethermind JSON RPC"); } if (ctx.Request.Method == "POST" && jsonRpcUrlCollection.TryGetValue(ctx.Connection.LocalPort, out JsonRpcUrl jsonRpcUrl) && jsonRpcUrl.RpcEndpoint.HasFlag(RpcEndpoint.Http)) { if (jsonRpcUrl.IsAuthenticated && !rpcAuthentication !.Authenticate(ctx.Request.Headers["Authorization"])) { var response = jsonRpcService.GetErrorResponse(ErrorCodes.ParseError, "Authentication error"); ctx.Response.ContentType = "application/json"; ctx.Response.StatusCode = StatusCodes.Status200OK; jsonSerializer.Serialize(ctx.Response.Body, response); await ctx.Response.CompleteAsync(); return; } Stopwatch stopwatch = Stopwatch.StartNew(); using CountingTextReader request = new(new StreamReader(ctx.Request.Body, Encoding.UTF8)); try { await foreach (JsonRpcResult result in jsonRpcProcessor.ProcessAsync(request, JsonRpcContext.Http(jsonRpcUrl))) { using (result) { Stream resultStream = jsonRpcConfig.BufferResponses ? new MemoryStream() : ctx.Response.Body; long responseSize; try { ctx.Response.ContentType = "application/json"; ctx.Response.StatusCode = GetStatusCode(result); responseSize = result.IsCollection ? jsonSerializer.Serialize(resultStream, result.Responses) : jsonSerializer.Serialize(resultStream, result.Response); if (jsonRpcConfig.BufferResponses) { ctx.Response.ContentLength = responseSize = resultStream.Length; resultStream.Seek(0, SeekOrigin.Begin); await resultStream.CopyToAsync(ctx.Response.Body); } } catch (Exception e) when(e.InnerException is OperationCanceledException) { responseSize = SerializeTimeoutException(jsonRpcService, resultStream); } catch (OperationCanceledException) { responseSize = SerializeTimeoutException(jsonRpcService, resultStream); } finally { await ctx.Response.CompleteAsync(); if (jsonRpcConfig.BufferResponses) { await resultStream.DisposeAsync(); } } long handlingTimeMicroseconds = stopwatch.ElapsedMicroseconds(); if (result.IsCollection) { jsonRpcLocalStats.ReportCalls(result.Reports); jsonRpcLocalStats.ReportCall(new RpcReport("# collection serialization #", handlingTimeMicroseconds, true), handlingTimeMicroseconds, responseSize); } else { jsonRpcLocalStats.ReportCall(result.Report, handlingTimeMicroseconds, responseSize); } Interlocked.Add(ref Metrics.JsonRpcBytesSentHttp, responseSize); } // There should be only one response because we don't expect multiple JSON tokens in the request break; } } catch (Microsoft.AspNetCore.Http.BadHttpRequestException e) { if (logger.IsDebug) { logger.Debug($"Couldn't read request.{Environment.NewLine}{e}"); } } finally { Interlocked.Add(ref Metrics.JsonRpcBytesReceivedHttp, ctx.Request.ContentLength ?? request.Length); } } }); }
public void PlayWithTimeSynchronization(Dictionary <long, List <KeyEvent> > keyPlaybackBuffer) { if (!Playing) { KeyPlayingTask = Task.Run( async() => { var currentTimestamp = 0L; var keyInputSequences = KeyInputSequencer.BuildSequence(keyPlaybackBuffer); var enumerator = keyInputSequences.GetEnumerator(); SW = new Stopwatch(); SW.Start(); while (enumerator.MoveNext()) { try { // Sleep - Long Wait - Low CPU currentTimestamp = SW.ElapsedMicroseconds(); var millisecondsToSleep = (enumerator.Current.FrameTimestamp - currentTimestamp) / 1_000.0 - ThresholdAwaitTaskDelayInMilliseconds; if (millisecondsToSleep > SleepAccuracyAdjustmentInMicroseconds) { await Task.Delay((int)millisecondsToSleep).ConfigureAwait(false); } // Short Wait - High CPU while (SW.ElapsedMicroseconds() < enumerator.Current.FrameTimestamp - SleepAccuracyAdjustmentInMicroseconds) { /* NO-OP */ } currentTimestamp = SW.ElapsedMicroseconds(); var err = NativeMethods.SendInput( (uint)enumerator.Current.InputSequence.Length, enumerator.Current.InputSequence, Marshal.SizeOf(typeof(INPUT))); if (err > 1) { await KeyEventMessageChannelWriter .WriteAsync(string.Format(SendInputError, err)); } else { await KeyEventMessageChannelWriter .WriteAsync( string.Format(KeySequenceInputLog, enumerator.Current.KeySequence, currentTimestamp)); } } catch (Exception ex) { await KeyEventMessageChannelWriter .WriteAsync( string.Format(UknownError, ex.Message, ex.StackTrace)); } } Playing = false; }); } }