public async Task TestBatchRequestAggregator() { var btp = new BatchRequestAggregator(4); var sw = Stopwatch.StartNew(); var bag = new ConcurrentBag <int>(); var proxy = btp.GetBuilder <int, string>(async xs => { await Task.Delay(100); Console.WriteLine("batch size: {0}, @{1}, by thread:{2}", xs.Count, sw.ElapsedMilliseconds, Thread.CurrentThread.ManagedThreadId); bag.Add(xs.Count); return((from x in xs select x.ToString()).ToList()); }).WithMaxBatchSize(50).Create(); var tasks = (from t in Enumerable.Range(0, 100) select proxy.InvokeAsync(Enumerable.Range(t, 10).ToList())).ToArray(); await Task.WhenAll(tasks); Console.WriteLine("Total: {0}ms", sw.ElapsedMilliseconds); Console.WriteLine("Average size: {0}", bag.Average()); Assert.IsTrue(sw.ElapsedMilliseconds > 200, "Pool not effective!"); Assert.IsTrue(sw.ElapsedMilliseconds < 1000, "Merge not effective!"); Assert.IsTrue(bag.Average() > 30.0, "Merge not effective!"); for (int i = 0; i < tasks.Length; i++) { var results = tasks[i].Result; for (int j = 0; j < 10; j++) { Assert.AreEqual((i + j).ToString(), results[j], "Error at {0}-{1}, Expected:{2}, Actual:{3}", i, j, (i + j).ToString(), results[j]); } } }
static void Main(string[] args) { string countStr; do { Console.Write("请输入启动线程数:"); countStr = Console.ReadLine(); int count = Convert.ToInt32(countStr); int times = 0; do { Semaphore task = new Semaphore(0, count); Semaphore wait = new Semaphore(0, count); for (int i = 0; i < count; i++) { new Thread(Send).Start(new Tuple <Semaphore, Semaphore>(task, wait)); } task.Release(count); Console.WriteLine("请等待线程执行结束"); WaitAll(wait, count); Console.WriteLine("平均耗时:{0}", list.Average()); } while (++times < 100); Console.WriteLine("总平均耗时:{0}", list.Average()); } while (true); }
private async Task StartSimulation() { if (Simulator.SongData == null) { MessageBox.Show("楽曲を選んでください"); return; } if (Simulator.Unit == null) { MessageBox.Show("ユニットを選んでください"); return; } if (Runs < 1 || Runs > 1000000) { MessageBox.Show("試行回数は1から1,000,000までである必要があります"); return; } Note[] pattern = null; if (UtilizeActualPattern) { pattern = await new PatternProvider().GetPattern(Simulator.Song, Simulator.SongData.Difficulty, Simulator.SongData.Notes); if (pattern == null) { MessageBox.Show($"{Simulator.Song.Title}({Simulator.SongData.Difficulty})の譜面データが見つかりませんでした。"); return; } } SimulationCompleted = false; var results = new ConcurrentBag <SimulationResult>(); await Task.Run(() => Parallel.For(1, Runs + 1, i => results.Add(Simulator.StartSimulation(RandomFactory.Create(), i, pattern == null ? null : new Queue <Note>(pattern))))); MaxScore = results.Max(x => x.Score); MaxScorePerNote = results.Max(x => x.ScorePerNote); MinScore = results.Min(x => x.Score); MinScorePerNote = results.Min(x => x.ScorePerNote); AverageScore = (int)results.Average(x => x.Score); AverageScorePerNote = (int)results.Average(x => x.ScorePerNote); ScoreDistribution = results.GroupBy(x => (int)Math.Floor(x.Score / 10000.0)).OrderBy(x => x.Key).ToDictionary(x => x.Key, x => (double)x.Count() / results.Count); StandardDeviation = Math.Round(Math.Sqrt(results.Sum(x => Math.Pow(x.Score - AverageScore, 2))) / results.Count); int idx = 1; var duration = results.First().Duration; ActualTriggerRatio = Simulator.Unit.Slots.ToDictionary(s => $"スロット{idx++}", s => s == null ? 0 : results.SelectMany(x => x.TriggeredSkills).Where(x => x.Who == s).Count() / (results.Count * Math.Floor((duration - 1.0) / s.Skill.Interval))); SimulationResults = results.OrderBy(x => x.Id).Take(100).ToList(); SelectedResult = SimulationResults[0]; SimulationCompleted = true; }
static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; var timer = new Timer(StatusCheck, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5)); rand = new Random(); cts = new CancellationTokenSource(); cts.Token.Register(CancelThreads); foreach (var i in Enumerable.Range(0, 10)) { DoTestBatch(); } while (open > 1) { Thread.Sleep(250); } Console.WriteLine("Done " + sent); timer.Change(TimeSpan.FromMilliseconds(-1), TimeSpan.FromMilliseconds(-1)); Console.WriteLine("Avg Chat " + WatchBag.Average()); Console.WriteLine("Min " + WatchBag.Min()); Console.WriteLine("Max " + WatchBag.Max()); Console.ReadLine(); }
private static void MultiThreadPerformanceTest(IFixedSizeCache<string, int> cache, int loopCount) { ConcurrentBag<long> allTickTimes = new ConcurrentBag<long>(); ConcurrentBag<long> allElapsedTimesMilliseconds = new ConcurrentBag<long>(); Parallel.For(0, 25, i => { Task.Run(() => TimeParralelCacheWrite(cache, loopCount)); Stopwatch timer = TimeParralelCacheWrite(cache, loopCount); allTickTimes.Add(timer.ElapsedTicks); allElapsedTimesMilliseconds.Add(timer.ElapsedMilliseconds); }); double averageTickTime = allTickTimes.Average(); double averageTimeMilliseconds = allElapsedTimesMilliseconds.Average(); Console.WriteLine("Average ticks: " + averageTickTime); Console.WriteLine("Average ms: " + averageTimeMilliseconds); //Assert.That(averageTickTime, Is.LessThanOrEqualTo(3005055)); //Assert.That(averageTimeMilliseconds, Is.LessThanOrEqualTo(1826)); //spinlock > normal lock > MemoryCache > flashcaches Assert.That(cache.CacheItemCount, Is.LessThanOrEqualTo(300000)); }
static void Main(string[] args) { var asyncProcessor = new AsyncProcessor(5, TimeSpan.FromSeconds(5)); var totalTime = Stopwatch.StartNew(); var threads = new List <Task>(); for (int i = 0; i < 40; i++) { var task = Task.Run(async() => { var request = new Request(); try { lock (_rnd) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"{request} Program Sending a Request. FreeChannel: {asyncProcessor.FreeChannel}"); } var response = await asyncProcessor.RemoteCall(request); lock (_rnd) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"{response} Program Receiving a Response. FreeChannel: {asyncProcessor.FreeChannel} Type {request.Type}"); } _responses.Add(response); } catch (OperationCanceledException) { lock (_rnd) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"{request} RemoteCall Cancelled. FreeChannel: {asyncProcessor.FreeChannel} Type {request.Type}"); } Interlocked.Increment(ref _cancelCount); } catch (Exception ex) { Console.WriteLine($"{request} Failed. {ex.GetType().Name}: {ex.Message}\r\n{ex.StackTrace}"); } }); Thread.Sleep(_rnd.Next(100, 2000)); threads.Add(task); } lock (_rnd) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Wait all task to finish."); } Task.WaitAll(threads.ToArray()); totalTime.Stop(); lock (_rnd) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"All task completed. TotalTime: {totalTime.Elapsed}"); var avg = TimeSpan.FromMilliseconds(_responses.Count > 0 ? _responses.Average(e => e.ResponseTime.TotalMilliseconds) : 0); Console.WriteLine($"Average: {avg} Completed/Cancelled: {_responses.Count}/{_cancelCount}"); } }
private static void ShowStats(SynchedColouredConsoleTraceWriter synchedConsole) { synchedConsole.WriteLine($@" Following results & performance based on a {100.0 / _perTestMeasureEveryN:#0.0}% sample ({MonitoredWorkBag.Count:#,##0}) + all timeouts & faulted requests. Results & performance of sample... Total: {MonitoredWorkBag.Count:#,##0}, Completed: {MonitoredWorkBag.Count(t => t.Item1.IsCompleted):#,##0}, Faulted: {MonitoredWorkBag.Count(t => t.Item1.IsFaulted):#,##0}, Cancelled: {MonitoredWorkBag.Count(t => t.Item1.IsCanceled):#,##0}, Performance (microseconds [us] - thousandaths of milliseconds / millionths of seconds) Fastest: {MonitoredWorkBag.Min(t => t.Item2.TotalMilliseconds * 1000):#,##0.0} (us), Slowest: {MonitoredWorkBag.Max(t => t.Item2.TotalMilliseconds * 1000):#,##0.0} (us), Average time: {MonitoredWorkBag.Average(t => t.Item2.TotalMilliseconds * 1000):#,##0.0} (us), Median: {Percentile(MonitoredWorkBag.Select(t => t.Item2.TotalMilliseconds * 1000), 0.50):#,##0.0} (us), P75: {Percentile(MonitoredWorkBag.Select(t => t.Item2.TotalMilliseconds * 1000), 0.75):#,##0.0} (us), P90: {Percentile(MonitoredWorkBag.Select(t => t.Item2.TotalMilliseconds * 1000), 0.90):#,##0.0} (us), P95: {Percentile(MonitoredWorkBag.Select(t => t.Item2.TotalMilliseconds * 1000), 0.95):#,##0.0} (us), P99: {Percentile(MonitoredWorkBag.Select(t => t.Item2.TotalMilliseconds * 1000), 0.99):#,##0.0} (us), P3x9: {Percentile(MonitoredWorkBag.Select(t => t.Item2.TotalMilliseconds * 1000), 0.999):#,##0.0} (us), P5x9: {Percentile(MonitoredWorkBag.Select(t => t.Item2.TotalMilliseconds * 1000), 0.99999):#,##0.0} (us), ", overrideShowOutput: true); }
private async Task <double> ExecuteTestsAsync(string name, Func <Uri, Task> runAsync) { const int iterationCount = 5 + 1; var results = new ConcurrentBag <Result>(); for (var iteration = 0; iteration < iterationCount; iteration++) { await RunIteration(name, iteration, runAsync, iteration > 0?results : null); } using (var fileStream = new FileStream(_fileName, FileMode.Append)) using (var streamReader = new StreamWriter(fileStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true))) using (var csvWriter = new CsvWriter(streamReader)) { if (!_wroteHeader) { csvWriter.WriteHeader <Result>(); csvWriter.NextRecord(); _wroteHeader = true; } foreach (var result in results.OrderBy(x => x.Name).ThenBy(x => x.Iteration).ThenBy(x => x.Sequence)) { csvWriter.WriteRecord(result); csvWriter.NextRecord(); } } var average = results.Average(x => x.DurationMs); _output.WriteLine($"{name}: average = {average}"); return(average); }
private void LogTemplates(ConcurrentBag <long> speedLogs, int totalCount) { Log($"Max: {speedLogs.Max():n0} ms"); Log($"Min: {speedLogs.Min():n0} ms"); Log($"Avg: {speedLogs.Average():n3} ms"); Log($"Total: {speedLogs.Sum():n0} ms"); Log($"InsertsInSecond: {speedLogs.Count() / (speedLogs.Sum() / (double) 1000):n3}"); Log($"Success: {speedLogs.Count():n0}/{totalCount:n0}\n"); }
public static async Task Parallel(int numUsers, int numIterationsPerUser, Func <Task> action, int expectedAvg = 100, ITestOutputHelper testOutput = null) { await action(); var elapsedMs = new ConcurrentBag <long>(); var errors = 0; async Task RunAsync() { for (var i = 0; i < numIterationsPerUser; i++) { try { var watch = Stopwatch.StartNew(); await action(); watch.Stop(); elapsedMs.Add(watch.ElapsedMilliseconds); } catch { Interlocked.Increment(ref errors); } } } var tasks = new List <Task>(); for (var i = 0; i < numUsers; i++) { tasks.Add(Task.Run(RunAsync)); } await Task.WhenAll(tasks); var count = elapsedMs.Count; var avg = elapsedMs.Average(); if (testOutput != null) { testOutput.WriteLine("Total Errors: {0}/{1}", errors, numUsers * numIterationsPerUser); testOutput.WriteLine("Total Count: {0}/{1}", count, numUsers * numIterationsPerUser); testOutput.WriteLine(string.Empty); testOutput.WriteLine("Performance Average: {0}", avg); testOutput.WriteLine("Performance Max: {0}", elapsedMs.Max()); testOutput.WriteLine("Performance Min: {0}", elapsedMs.Min()); } Assert.InRange(avg, 0, expectedAvg); }
public void TestConcurrent() { var serializerRepresentation = GetSerializerRepresentation(); var tags = new List <NamedValue <string> > { new NamedValue <string>("ChangeSet", Guid.NewGuid().ToString().ToUpperInvariant()), }; var timestampUtc = DateTime.UtcNow; var payloadType = typeof(byte[]).ToRepresentation(); var metadata = new StreamRecordMetadata( Guid.NewGuid().ToString().ToUpperInvariant(), serializerRepresentation, typeof(string).ToRepresentation().ToWithAndWithoutVersion(), payloadType.ToWithAndWithoutVersion(), tags, timestampUtc, timestampUtc); var payload = new BinaryDescribedSerialization(payloadType, serializerRepresentation, new byte[3000000]); var putOp = new StandardPutRecordOp(metadata, payload); var commandTimeout = TimeSpan.FromSeconds(1000); var listOfStreams = Enumerable.Range(1, 10) .Select( _ => this.GetCreatedSqlStream( commandTimeout, RecordTagAssociationManagementStrategy.ExternallyManaged)) .ToList(); var times = new ConcurrentBag <TimeSpan>(); Parallel.ForEach(listOfStreams, _ => { var stopwatch = new Stopwatch(); for (var idx = 0; idx < 100; idx++) { stopwatch.Reset(); stopwatch.Start(); _.Execute(putOp); stopwatch.Stop(); times.Add(stopwatch.Elapsed); } }); var averageSeconds = times.Average(_ => _.TotalSeconds); var minSeconds = times.Min(_ => _.TotalSeconds); var maxSeconds = times.Max(_ => _.TotalSeconds); this.testOutputHelper.WriteLine(Invariant($"{nameof(averageSeconds)}: {averageSeconds}, {nameof(minSeconds)}: {minSeconds}, {nameof(maxSeconds)}: {maxSeconds}, ")); foreach (var time in times) { this.testOutputHelper.WriteLine(time.TotalSeconds.ToString(CultureInfo.InvariantCulture)); } }
private static async Task GetStatsTask(ConcurrentBag <Tester> testers, int count, NLog.Logger logger, DateTime startTime) { double?maxRate = null; double?minRate = null; // initializing: while (true) { await Task.Delay(2000); var now = DateTime.Now; var currentCount = testers.Count; var elapsed = (now - startTime).TotalMilliseconds / 1000; var currentRate = currentCount / elapsed; if (maxRate == null || maxRate < currentRate) { maxRate = currentRate; } if (minRate == null || minRate > currentRate) { minRate = currentRate; } logger.Info($"Starts {currentCount}/{count}, current {currentRate:.00}/s, max {maxRate:.00}/s, min {minRate:.00}/s; " + $"Connect Elapsed: max {testers.Max(s => s.ConnectStats.MaxElapsed):.00}, min {testers.Min(s => s.ConnectStats.MinElapsed):.00}, avg {testers.Average(s => s.ConnectStats.AvgElapsed):.00}"); LogExceptions(testers, logger); if (currentCount == count) { break; } } // running: // aggregate exception count while (true) { await Task.Delay(2000); logger.Info($"[connected]{testers.Count(s => s.IsConnected)}/[connecting]{testers.Count(s => s.IsConnecting)}/[total]{count};" + $" sending {testers.Sum(s => s.SendMessageStats.ReceivedCount)} messages" + $"\n\t Delay: avergae {testers.Average(s => s.SendMessageStats.AvgElapsed)}, " + $" max {testers.Max(s => s.SendMessageStats.MaxElapsed)}, min {testers.Min(s => s.SendMessageStats.MinElapsed)} " + $"\n\tSend: max success {testers.Max(s => s.SendMessageStats.SuccessCount)}; max notsent {testers.Max(s => s.SendMessageStats.NotSentCount)}; max error {testers.Max(s => s.SendMessageStats.ErrorCount)};" + $"\n\tNotReceived: max {testers.Max(s => s.SendMessageStats.SuccessCount - s.SendMessageStats.ReceivedCount)}"); if (testers.Any(s => s.ReconnectCount > 0)) { logger.Info($"\n\tReconnect: max: {testers.Max(s => s.RecoverStats.MaxElapsed)}, avg: {testers.Average(s => s.RecoverStats.AvgElapsed)} "); } LogExceptions(testers, logger); } }
public void CountSortDecisionsTest() { int setLength = 11; int sortAttempts = 1000; var decisionCounts = new ConcurrentBag<int>(); Parallel.ForEach(Enumerable.Range(0, sortAttempts), attempt => { var integerComparableList = Enumerable.Range(0, setLength) .RandomiseOrder() .Select(i => new IntegerAbstractComparable(i)) .ToArray(); bool completed = false; int decisions = 0; SortResult<IntegerAbstractComparable> orderedIntegerComparableSortResult = null; while (!completed) { orderedIntegerComparableSortResult = orderService.OrderObjects(integerComparableList); completed = orderedIntegerComparableSortResult.Completed; if (!completed) { if (orderedIntegerComparableSortResult.LeftSort.Value > orderedIntegerComparableSortResult.RightSort.Value) { orderedIntegerComparableSortResult.RightSort.AddHigherRankedObject(orderedIntegerComparableSortResult.LeftSort); } else { orderedIntegerComparableSortResult.LeftSort.AddHigherRankedObject(orderedIntegerComparableSortResult.RightSort); } decisions++; } } var expectedIntegerComparableList = integerComparableList.OrderBy(i => i.Value).ToArray(); // asserts Assert.IsTrue(orderedIntegerComparableSortResult.Completed); CollectionAssert.AreEquivalent(expectedIntegerComparableList, orderedIntegerComparableSortResult.SortedResults.ToArray()); decisionCounts.Add(decisions); }); var averageDecision = decisionCounts.Average(); var minDecision = decisionCounts.Min(); var maxDecision = decisionCounts.Max(); var diff = maxDecision - minDecision; Console.WriteLine(averageDecision); // quick sort - 35.519 // 13 // 53 // merge sort // min 17 // max 52 }
private static void TestSortAlgorithm( int setLength, int sortAttempts, ISortAlgorithm <IntegerAbstractComparable> sortAlgorithm) { var orderService = new OrderService(); var decisionCounts = new ConcurrentBag <int>(); Parallel.ForEach(Enumerable.Range(0, sortAttempts), attempt => { var integerComparableList = Enumerable.Range(0, setLength) .RandomiseOrder() .Select(i => new IntegerAbstractComparable(i)) .ToArray(); bool completed = false; int decisions = 0; SortResult <IntegerAbstractComparable> orderedIntegerComparableSortResult = null; while (!completed) { orderedIntegerComparableSortResult = orderService .OrderObjects(integerComparableList, sortAlgorithm); completed = orderedIntegerComparableSortResult.Completed; if (!completed) { if (orderedIntegerComparableSortResult.LeftSort.Value > orderedIntegerComparableSortResult.RightSort.Value) { orderedIntegerComparableSortResult.RightSort.AddHigherRankedObject(orderedIntegerComparableSortResult.LeftSort); } else { orderedIntegerComparableSortResult.LeftSort.AddHigherRankedObject(orderedIntegerComparableSortResult.RightSort); } decisions++; } } var expectedIntegerComparableList = integerComparableList.OrderBy(i => i.Value).ToArray(); // asserts Assert.IsTrue(orderedIntegerComparableSortResult.Completed); CollectionAssert.AreEquivalent(expectedIntegerComparableList, orderedIntegerComparableSortResult.SortedResults.ToArray()); decisionCounts.Add(decisions); }); var averageDecision = decisionCounts.Average(); var minDecision = decisionCounts.Min(); var maxDecision = decisionCounts.Max(); var diff = maxDecision - minDecision; Console.WriteLine($"{sortAlgorithm.GetType().Name} average decisions: {averageDecision} minimum decisions: {minDecision} maximum decisions: {maxDecision}"); }
private static async Task GetStatsTask(ConcurrentBag <Tester> testers, int count, NLog.Logger logger, DateTime startTime) { double?maxRate = null; double?minRate = null; // initializing: while (true) { await Task.Delay(2000); var now = DateTime.Now; var currentCount = testers.Count; var elapsed = (now - startTime).TotalMilliseconds / 1000; var currentRate = currentCount / elapsed; if (maxRate == null || maxRate < currentRate) { maxRate = currentRate; } if (minRate == null || minRate > currentRate) { minRate = currentRate; } var sb = new StringBuilder(); sb.Append($"Starts {currentCount}/{count}, current {currentRate:.00}/s, max {maxRate:.00}/s, min {minRate:.00}/s; " + $"Connect Elapsed: max {testers.Max(s => s.ConnectStats.MaxElapsed):.00}, min {testers.Min(s => s.ConnectStats.MinElapsed):.00}, avg {testers.Average(s => s.ConnectStats.AvgElapsed):.00}"); sb = LogExceptions(testers, sb); logger.Info(sb); if (currentCount == count) { break; } } // running: // aggregate exception count while (true) { await Task.Delay(2000); var sb = new StringBuilder(); sb.Append($"\n\t[connected]{testers.Count(s => s.ConnectStatus == Status.Connected)}/[connecting]{testers.Count(s => s.ConnectStatus == Status.Connecting)}/[disconnected]{testers.Count(s => s.ConnectStatus == Status.Disconnected)}/[total]{count};" + $"\n\t[send]{testers.Sum(s => s.SendMessageStats.ReceivedCount)} messages," + $" avg {testers.Average(s => s.SendMessageStats.AvgElapsed)}ms, " + $" max {testers.Max(s => s.SendMessageStats.MaxElapsed)}ms, min {testers.Min(s => s.SendMessageStats.MinElapsed)}ms " + $"\n\t[send]max success {testers.Max(s => s.SendMessageStats.SuccessCount)}; max not sent {testers.Max(s => s.SendMessageStats.NotSentCount)}; max error {testers.Max(s => s.SendMessageStats.ErrorCount)};" + $" max not received {testers.Max(s => s.SendMessageStats.SuccessCount - s.SendMessageStats.ReceivedCount)}"); sb = LogExceptions(testers, sb); logger.Info(sb); } }
public static void Run() { var numbers = new ConcurrentBag <double>(); Parallel.For(0, 100000, i => numbers.Add(new Random().NextDouble())); var avg = numbers.Average(); Console.WriteLine($"The average is {avg}."); Console.ReadLine(); }
public static double GetTraseholdByHistogram( this Bitmap image, double startTrasehold, double delta) { double currentTrasehold = startTrasehold; ConcurrentBag <double> G1 = new ConcurrentBag <double>(); ConcurrentBag <double> G2 = new ConcurrentBag <double>(); List <Task> tasks = new List <Task>(); List <Bitmap> imageRectangles = new List <Bitmap>(); int partSize = image.Width % 8 == 0 ? image.Width / 8 : image.Width / 8 + 1; for (int i = 0; i < 8; i++) { imageRectangles.Add(GetImageRectangle(image, i * partSize, (image.Width % 8 != 0 && i == 7) ? image.Width - (7 * partSize) : partSize)); } while (true) { for (int i = 0; i < 8; i++) { int m = i; tasks.Add(new Task(() => { int startIndex = m * partSize; ParallelImage(currentTrasehold, G1, G2, imageRectangles[m]); })); } foreach (var task in tasks) { task.Start(); } Task.WaitAll(tasks.ToArray()); var tempTrasehold = (G1.Average() + G2.Average()) / 2.0; if (Math.Abs(currentTrasehold - tempTrasehold) < delta) { return(tempTrasehold); } currentTrasehold = tempTrasehold; G1 = new ConcurrentBag <double>(); G2 = new ConcurrentBag <double>(); tasks = new List <Task>(); } }
private static async Task Run(int numUsers, int numIterationsPerUser, Func <Task> action, int expectedAvg = 100) { var elapsedMs = new ConcurrentBag <long>(); var errors = 0; async Task RunAsync() { for (var i = 0; i < numIterationsPerUser; i++) { try { var watch = Stopwatch.StartNew(); await action(); watch.Stop(); elapsedMs.Add(watch.ElapsedMilliseconds); } catch { Interlocked.Increment(ref errors); } } } var tasks = new List <Task>(); for (var i = 0; i < numUsers; i++) { tasks.Add(Task.Run(RunAsync)); } await Task.WhenAll(tasks); var count = elapsedMs.Count; var max = elapsedMs.Max(); var min = elapsedMs.Min(); var avg = elapsedMs.Average(); Assert.Equal(0, errors); Assert.Equal(count, numUsers * numIterationsPerUser); Assert.InRange(max, 0, expectedAvg * 10); Assert.InRange(min, 0, expectedAvg); Assert.InRange(avg, 0, expectedAvg); }
public void SpeedLimitTest() { var speedPerSecondsHistory = new ConcurrentBag <long>(); var lastTick = 0L; var expectedFileSize = DownloadTestHelper.FileSize10Mb; // real bytes size var address = DownloadTestHelper.File10MbUrl; var file = new FileInfo(Path.GetTempFileName()); var config = new DownloadConfiguration() { BufferBlockSize = 1024, ChunkCount = 8, ParallelDownload = true, MaxTryAgainOnFailover = 100, OnTheFlyDownload = true, MaximumBytesPerSecond = 1024 * 1024 // 1MB/s }; var progressCount = config.ChunkCount * (int)Math.Ceiling((double)expectedFileSize / config.ChunkCount / config.BufferBlockSize); var downloader = new DownloadService(config); downloader.DownloadProgressChanged += (s, e) => { Interlocked.Decrement(ref progressCount); if (Environment.TickCount64 - lastTick >= 1000) { speedPerSecondsHistory.Add(e.BytesPerSecondSpeed); lastTick = Environment.TickCount64; } }; downloader.DownloadFileAsync(address, file.FullName).Wait(); // wait to download stopped! var avgSpeed = (long)speedPerSecondsHistory.Average(); Assert.IsTrue(file.Exists); Assert.AreEqual(expectedFileSize, downloader.Package.TotalFileSize); Assert.AreEqual(expectedFileSize, file.Length); Assert.IsTrue(progressCount <= 0); Assert.IsTrue(avgSpeed <= config.MaximumBytesPerSecond); if (File.Exists(file.FullName)) { try { file.Delete(); } catch (Exception e) { Console.WriteLine(e); } } }
public static void Main(string[] args) { //setup mqtt client SetupMqtt(); //run simulator in another thread var simulatedSensor = new Task(() => LoopDeviceSimulator()); simulatedSensor.Start(); //filter if mqtt data is coming var FilteredSensorData = from x in WhenDataReceived let node = JsonConvert.DeserializeObject <SensorData>(new string(Encoding.UTF8.GetChars(x.Message))) where node.Temp > 50 select x; //create window for 5 seconds var WindowedData = FilteredSensorData .Window(() => { var seqWindowControl = Observable.Interval(TimeSpan.FromSeconds(6)); return(seqWindowControl); }); var TempRate = new ConcurrentBag <int>(); //subscribe WindowedData .Subscribe(seqwindow => { Console.WriteLine($"Data from {DateTime.Now.AddSeconds(-5)} to {DateTime.Now}"); if (TempRate.Count > 0) { Console.WriteLine( $"average temperature in 5 secs: {TempRate.Count} items at {TempRate.Average()}"); int someItem; while (!TempRate.IsEmpty) { TempRate.TryTake(out someItem); } } seqwindow.Subscribe(e => { var msg = new string(Encoding.UTF8.GetChars(e.Message)); Console.WriteLine($"{e.Topic} -> {msg}"); var node = JsonConvert.DeserializeObject <SensorData>(msg); TempRate.Add(node.Temp); }); }); //infinite delay Thread.Sleep(Timeout.Infinite); }
private void Count() { var codeGroup = _counter.GroupBy(x => x.Response.StatusCode); var codeGroupList = new List <string>(); foreach (var item in codeGroup) { codeGroupList.Add(string.Format("[{0}]:{1}", item.Key, item.Count())); } _console("Http状态码统计:" + string.Join(",", codeGroupList)); var total = _counter.Count; var avgElapsed = _counter.Average(x => x.MilliSeconds); _console(string.Format("总请求数:{0},平均耗时:{1}ms", total, avgElapsed.ToString("0.000"))); }
public static void GetStatistics(IStrategy strategy, out double avg, out double stdDev, out double coeffVariation) { var numTests = Settings.Current.TestSettings.NumTests; var scores = new ConcurrentBag <double>(); Parallel.For(0, numTests, i => { var score = Test(strategy); scores.Add(score); }); avg = scores.Average(); stdDev = scores.StandardDeviation(); coeffVariation = stdDev / avg; }
public async Task LogAction(double obj) { _temperatureReadings.Add(obj); if (_temperatureReadings.Count >= 2) { var average = _temperatureReadings.Average(); _temperatureReadings = new ConcurrentBag <double>(); foreach (var action in _childLoggerActions) { await action.LogAction(average); } } }
// other options for perf. // 1) only grab certain directories either with dockerfiles or as specified by build.yaml // 2) Prioritize large files or files with lots of copies. // 3) parallelize copy with buffer first attempt at that with _contentClient.GetBufferAsync failed. Also lots of memory. // 4) multistream copyasync public async Task <Dictionary <string, double> > Materialize(string localDestination) { var uniqueblobs = _files.GroupBy(keySelector: file => file.Blob.Id, resultSelector: (key, file) => file).ToList(); var metrics = new Dictionary <string, double> { ["files"] = _files.Count, ["uniqueblobs"] = uniqueblobs.Count }; if (_computeDockerHashes) { ComputeDockerHashes(localDestination, metrics); } var dltimes = new ConcurrentBag <double>(); var copytimes = new ConcurrentBag <double>(); var filesize = new ConcurrentBag <double>(); var throttler = new ActionBlock <IEnumerable <VstsFile> >(list => DownloadGrouping(list, localDestination, dltimes, copytimes, filesize), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = _concurrentDownloads }); foreach (var grouping in uniqueblobs) { throttler.Post(grouping); } throttler.Complete(); await throttler.Completion; if (dltimes.Any()) { metrics["DownloadCount"] = dltimes.Count(); metrics["AverageDownloadSecs"] = dltimes.Average(); metrics["MaxDownloadSecs"] = dltimes.Max(); CalculatePercentile(metrics, dltimes, "Download"); } if (copytimes.Any()) { metrics["CopyCount"] = copytimes.Count(); metrics["AverageCopySecs"] = copytimes.Average(); metrics["MaxCopySecs"] = copytimes.Max(); CalculatePercentile(metrics, copytimes, "CopyTime"); } return(metrics); }
public async Task CreateRaceConditionsAsync() { int i = 0, s = 0; var o = new object(); var incrementorTimes = new ConcurrentBag <TimeSpan>(); var synchronizedIncrementorTimes = new ConcurrentBag <TimeSpan>(); // closure on i will create a race condition if multiple threads call incrementor simultaneously Action incrementor = () => { var start = DateTime.Now; for (var j = 0; j < 10000000; ++j) { ++i; } incrementorTimes.Add(DateTime.Now - start); }; Action synchronizedIncrementor = () => { var start = DateTime.Now; for (var j = 0; j < 10000000; ++j) { // use a lock to synchronize lock (o) { ++s; } } synchronizedIncrementorTimes.Add(DateTime.Now - start); }; // kick off 3 incrementer tasks and 3 synchronized incrementer tasks await Task.WhenAll(Task.Factory.StartNew(incrementor), Task.Factory.StartNew(incrementor), Task.Factory.StartNew(incrementor), Task.Factory.StartNew(synchronizedIncrementor), Task.Factory.StartNew(synchronizedIncrementor), Task.Factory.StartNew(synchronizedIncrementor)); Assert.NotEqual(30000000, i); Assert.Equal(30000000, s); // at least double run time for synchronized version (thread safety isn't free!) Assert.InRange(synchronizedIncrementorTimes.Average(t => t.TotalSeconds) / incrementorTimes.Average(t => t.TotalSeconds), 2.0, 100); }
public void PerformanceComparison() { var iterations = 100; var graphite = new ConcurrentBag <long>(); var graphiteAsync = new ConcurrentBag <long>(); var webapi = new ConcurrentBag <long>(); var webapiAsync = new ConcurrentBag <long>(); var guid = Guid.NewGuid(); var url = $"performancetests/{{0}}/url1/{guid}/5?query1=query1&query2={guid}&query3=5"; var urlAsync = $"performancetests/{{0}}/async/url1/{guid}/5?query1=query1&query2={guid}&query3=5"; var graphiteUrl = string.Format(url, "graphite"); var graphiteAsyncUrl = string.Format(urlAsync, "graphite"); var webapiUrl = string.Format(url, "webapi"); var webapiAsyncUrl = string.Format(urlAsync, "webapi"); var inputModel = new PerfInputModel { Value1 = "value1", Value2 = "value2", Value3 = "value3" }; 10.TimesParallel(() => { Should_match_result(WebClient.PostJson <PerfInputModel, PerfOutputModel>(graphiteUrl, inputModel), guid); Should_match_result(WebClient.PostJson <PerfInputModel, PerfOutputModel>(webapiUrl, inputModel), guid); Should_match_result(WebClient.PostJson <PerfInputModel, PerfOutputModel>(graphiteAsyncUrl, inputModel), guid); Should_match_result(WebClient.PostJson <PerfInputModel, PerfOutputModel>(webapiAsyncUrl, inputModel), guid); }); iterations.TimesParallel(() => { graphite.Add(graphiteUrl.ElapsedMilliseconds(x => WebClient.PostJson <PerfInputModel, PerfOutputModel>(x, inputModel))); webapi.Add(webapiUrl.ElapsedMilliseconds(x => WebClient.PostJson <PerfInputModel, Handler.OutputModel>(x, inputModel))); graphiteAsync.Add(graphiteUrl.ElapsedMilliseconds(x => WebClient.PostJson <PerfInputModel, PerfOutputModel>(x, inputModel))); webapiAsync.Add(webapiUrl.ElapsedMilliseconds(x => WebClient.PostJson <PerfInputModel, Handler.OutputModel>(x, inputModel))); }); Console.WriteLine($"Graphite : {graphite.Average()}ms"); Console.WriteLine($"Graphite Async: {graphiteAsync.Average()}ms"); Console.WriteLine($"Web Api: {webapi.Average()}ms"); Console.WriteLine($"Web Api Async: {webapiAsync.Average()}ms"); }
public static void Run() { var threads = new List <Thread>(); for (int i = 0; i < Environment.ProcessorCount; i++) { var thread = new Thread(Worker); threads.Add(thread); thread.Start(i); } foreach (var thread in threads) { thread.Join(); } var avg = _numbers.Average(); Console.WriteLine($"The average is {avg}."); Console.ReadLine(); }
static void RunLoadTest(TextLoadTest loadTest) { Console.WriteLine("Loading data...\n"); foreach (TextLoadTestData d in loadTest.Data) { dataInQueue.Enqueue(d); } Console.WriteLine("Spawning threads...\n"); for (int i = 0; i < loadTest.Threads; i++) { threads.Add(Task.Run(() => ThreadTextPostRequests(loadTest))); } Task.WaitAll(threads.ToArray()); Console.WriteLine("\nTest results:\n"); Console.WriteLine("Threads: {0}", loadTest.Threads); Console.WriteLine("Min: {0}", elapsedMilliseconds.Min()); Console.WriteLine("Max: {0}", elapsedMilliseconds.Max()); Console.WriteLine("Avg: {0}", elapsedMilliseconds.Average()); }
static void Main(string[] args) { var requestNumber = long.Parse(args[1]); var maxParallel = int.Parse(args[2]); var stats = new ConcurrentBag <long>(); var sw = new Stopwatch(); sw.Start(); Parallel.For(0, requestNumber, new ParallelOptions() { MaxDegreeOfParallelism = maxParallel }, (i) => { SendRequest(args[0], stats); }); sw.Stop(); Console.WriteLine($"Total time: {sw.ElapsedMilliseconds}ms"); Console.WriteLine($"Nb request/s: {(double)requestNumber/sw.ElapsedMilliseconds*1000.0}"); Console.WriteLine($"Avg Latency: {stats.Average()}"); Console.WriteLine($"Min Latency: {stats.Min()}"); Console.WriteLine($"Max Latency: {stats.Max()}"); }
static void Main(string[] args) { // to cover our back for all those fire and forgets TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; Console.ForegroundColor = ConsoleColor.Gray; ThreadPool.SetMinThreads(200, 100); ThreadPool.SetMaxThreads(1000, 200); var statusCodes = new ConcurrentBag<HttpStatusCode>(); var commandLineOptions = new CommandLineOptions(); bool isHelp = args.Any(x => x == "-?"); var success = Parser.Default.ParseArguments(args, commandLineOptions); var then = DateTime.Now; ConsoleWriteLine(ConsoleColor.DarkCyan, "Starting at {0}", then) ; if (!success || isHelp) { if (!isHelp && args.Length > 0) ConsoleWriteLine(ConsoleColor.Red, "error parsing command line"); return; } try { var requester = new Requester(commandLineOptions); var writer = new StreamWriter(commandLineOptions.LogFile) { AutoFlush = true }; var stopwatch = Stopwatch.StartNew(); var timeTakens = new ConcurrentBag<double>(); if (commandLineOptions.SaveResponses) { if (string.IsNullOrEmpty(commandLineOptions.ResponseFolder)) { commandLineOptions.ResponseFolder = Path.Combine(Environment.CurrentDirectory, "Responses"); } if (!Directory.Exists(commandLineOptions.ResponseFolder)) Directory.CreateDirectory(commandLineOptions.ResponseFolder); } ConsoleWriteLine(ConsoleColor.Yellow, "[Press C to stop the test]"); int total = 0; bool disrupted = false; var stop = new ConsoleKeyInfo(); Console.ForegroundColor = ConsoleColor.Cyan; var source = new CancellationTokenSource(TimeSpan.FromDays(7)); Task.Run(() => { stop = Console.ReadKey(true); disrupted = true; }, source.Token); var result = Parallel.For(0, commandLineOptions.IsDryRun ? 1 : commandLineOptions.NumberOfRequests, new ParallelOptions() { MaxDegreeOfParallelism = commandLineOptions.Concurrency }, (i, loopstate) => { if (disrupted) { ConsoleWriteLine(ConsoleColor.Red, "..."); ConsoleWriteLine(ConsoleColor.Green, "Exiting.... please wait! (it might throw a few more requests)"); ConsoleWriteLine(ConsoleColor.Red, ""); loopstate.Stop(); source.Cancel(); } var sw = Stopwatch.StartNew(); IDictionary<string, object> parameters; var statusCode = requester.Next(i, out parameters); sw.Stop(); if (commandLineOptions.DelayInMillisecond > 0) { Thread.Sleep(commandLineOptions.DelayInMillisecond); } statusCodes.Add(statusCode); timeTakens.Add(sw.ElapsedTicks); var n = Interlocked.Increment(ref total); // fire and forget not to affect time taken or TPS Task.Run(() => WriteLine(writer, n, (int)statusCode, sw.ElapsedMilliseconds, parameters)); if (!commandLineOptions.Verbose) Console.Write("\r" + total); } ); stopwatch.Stop(); double[] orderedList = (from x in timeTakens orderby x select x).ToArray<double>(); Console.WriteLine(); ConsoleWriteLine(ConsoleColor.Magenta, "---------------Finished!----------------"); var now = DateTime.Now; ConsoleWriteLine(ConsoleColor.DarkCyan, "Finished at {0} (took {1})", now, now - then); // ----- adding stats of statuses returned var stats = statusCodes.GroupBy(x => x) .Select(y => new { Status = y.Key, Count = y.Count() }).OrderByDescending(z => z.Count); foreach (var stat in stats) { int statusCode = (int)stat.Status; if (statusCode >= 400 && statusCode < 600) { ConsoleWriteLine(ConsoleColor.Red, string.Format("Status {0}: {1}", statusCode, stat.Count)); } else { ConsoleWriteLine(ConsoleColor.Green, string.Format("Status {0}: {1}", statusCode, stat.Count)); } } Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("TPS: " + Math.Round(total * 1000f / stopwatch.ElapsedMilliseconds, 1)); Console.WriteLine(" (requests/second)"); Console.WriteLine("Max: " + (timeTakens.Max() * 1000 / Stopwatch.Frequency) + "ms"); Console.WriteLine("Min: " + (timeTakens.Min() * 1000 / Stopwatch.Frequency) + "ms"); Console.WriteLine("Avg: " + (timeTakens.Average() * 1000 / Stopwatch.Frequency) + "ms"); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine(); Console.WriteLine(" 50%\tbelow " + Math.Round((double)((orderedList.Percentile<double>(50M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); Console.WriteLine(" 60%\tbelow " + Math.Round((double)((orderedList.Percentile<double>(60M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); Console.WriteLine(" 70%\tbelow " + Math.Round((double)((orderedList.Percentile<double>(70M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); Console.WriteLine(" 80%\tbelow " + Math.Round((double)((orderedList.Percentile<double>(80M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); Console.WriteLine(" 90%\tbelow " + Math.Round((double)((orderedList.Percentile<double>(90M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); Console.WriteLine(" 95%\tbelow " + Math.Round((double)((orderedList.Percentile<double>(95M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); Console.WriteLine(" 98%\tbelow " + Math.Round((double)((orderedList.Percentile<double>(98M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); Console.WriteLine(" 99%\tbelow " + Math.Round((double)((orderedList.Percentile<double>(99M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); Console.WriteLine("99.9%\tbelow " + Math.Round((double)((orderedList.Percentile<double>(99.9M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); } catch (Exception exception) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(exception); } Console.ResetColor(); }
private void RequestRiverBedHomePageMultiThreaded( IMethodLogger logger, int numberOfRequestsToMake, int numberOfThreads) { var requestTimes = new ConcurrentBag<long>(); int htmlLength = 0; try { Parallel.For(0, numberOfRequestsToMake, new ParallelOptions { MaxDegreeOfParallelism = numberOfThreads }, i => { var requestStopWatch = Stopwatch.StartNew(); var webClient = new WebClient(); using (var stream = webClient.OpenRead(new Uri("http://www.riverbed.com"))) // ReSharper disable once AssignNullToNotNullAttribute -- will handle in parent catch using (var sr = new StreamReader(stream)) { var html = sr.ReadToEnd(); htmlLength = html.Length; } requestTimes.Add(requestStopWatch.ElapsedMilliseconds); }); } catch (Exception e) { throw new Exception("Error getting http://www.riverbed.com: " + e.Message + Environment.NewLine + e.StackTrace); } logger.WriteMethodInfo( string.Format("Html Length [{0:n0}] chars. Request Times: Min [{1:n0}] Avg [{2:n0}] Max [{3:n0}]", htmlLength, requestTimes.Min(), requestTimes.Average(), requestTimes.Max())); logger.WriteMethodInfo(""); }
private static void WithOptionDoItBoy(CommandLineOptions commandLineOptions) { var statusCodes = new ConcurrentBag <HttpStatusCode>(); if (commandLineOptions.IsDryRun) { commandLineOptions.NumberOfRequests = 1; } if (commandLineOptions.TlsVersion.HasValue) { switch (commandLineOptions.TlsVersion.Value) { case 0: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; break; case 1: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11; break; case 2: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; break; case 3: ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; break; default: throw new InvalidOperationException("TLS version not supported."); } } var then = DateTime.Now; ConsoleWriteLine(ConsoleColor.DarkCyan, "Starting at {0}", then); try { var requester = string.IsNullOrEmpty(commandLineOptions.TimeField) ? (IAsyncRequester) new Requester(commandLineOptions) : (IAsyncRequester) new TimeBasedRequester(commandLineOptions); var writer = new StreamWriter(commandLineOptions.LogFile) { AutoFlush = false }; var stopwatch = Stopwatch.StartNew(); var timeTakens = new ConcurrentBag <double>(); if (commandLineOptions.SaveResponses) { if (string.IsNullOrEmpty(commandLineOptions.ResponseFolder)) { commandLineOptions.ResponseFolder = Path.Combine(Environment.CurrentDirectory, "Responses"); } if (!Directory.Exists(commandLineOptions.ResponseFolder)) { Directory.CreateDirectory(commandLineOptions.ResponseFolder); } } ConsoleWriteLine(ConsoleColor.Yellow, "[Press C to stop the test]"); int total = 0; var stop = new ConsoleKeyInfo(); Console.ForegroundColor = ConsoleColor.Cyan; var source = new CancellationTokenSource(TimeSpan.FromDays(7)); var logSourece = new CancellationTokenSource(TimeSpan.FromDays(7)); Task.Run(() => ProcessLogQueueAsync(writer, commandLineOptions.DontCapLoggingParameters, logSourece.Token), logSourece.Token); Task.Run(() => { while (true) { stop = Console.ReadKey(true); if (stop.KeyChar == 'c') { break; } } ConsoleWriteLine(ConsoleColor.Red, "..."); ConsoleWriteLine(ConsoleColor.Green, "Exiting.... please wait! (it might throw a few more requests)"); ConsoleWriteLine(ConsoleColor.Red, ""); source.Cancel(); }, source.Token); // NOT MEANT TO BE AWAITED!!!! Run(commandLineOptions, source, requester, statusCodes, timeTakens, total); total = timeTakens.Count; Console.WriteLine(); stopwatch.Stop(); ConsoleWriteLine(ConsoleColor.Magenta, "---------------Finished!----------------"); var now = DateTime.Now; ConsoleWriteLine(ConsoleColor.DarkCyan, "Finished at {0} (took {1})", now, now - then); // waiting for log to catch up Thread.Sleep(1000); source.Cancel(); double[] orderedList = (from x in timeTakens orderby x select x).ToArray <double>(); // ----- adding stats of statuses returned var stats = statusCodes.GroupBy(x => x) .Select(y => new { Status = y.Key, Count = y.Count() }).OrderByDescending(z => z.Count); foreach (var stat in stats) { int statusCode = (int)stat.Status; if (statusCode >= 400 && statusCode < 600) { ConsoleWriteLine(ConsoleColor.Red, string.Format("Status {0}: {1}", statusCode, stat.Count)); } else { ConsoleWriteLine(ConsoleColor.Green, string.Format("Status {0}: {1}", statusCode, stat.Count)); } } Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("TPS: " + Math.Round(total * 1000f / stopwatch.ElapsedMilliseconds, 1)); Console.WriteLine(" (requests/second)"); Console.WriteLine("Max: " + (timeTakens.Max() * 1000 / Stopwatch.Frequency) + "ms"); Console.WriteLine("Min: " + (timeTakens.Min() * 1000 / Stopwatch.Frequency) + "ms"); Console.WriteLine("Avg: " + (timeTakens.Average() * 1000 / Stopwatch.Frequency) + "ms"); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine(); Console.WriteLine(" 50%\tbelow " + Math.Round((double)((orderedList.Percentile <double>(50M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); Console.WriteLine(" 60%\tbelow " + Math.Round((double)((orderedList.Percentile <double>(60M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); Console.WriteLine(" 70%\tbelow " + Math.Round((double)((orderedList.Percentile <double>(70M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); Console.WriteLine(" 80%\tbelow " + Math.Round((double)((orderedList.Percentile <double>(80M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); Console.WriteLine(" 90%\tbelow " + Math.Round((double)((orderedList.Percentile <double>(90M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); Console.WriteLine(" 95%\tbelow " + Math.Round((double)((orderedList.Percentile <double>(95M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); Console.WriteLine(" 98%\tbelow " + Math.Round((double)((orderedList.Percentile <double>(98M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); Console.WriteLine(" 99%\tbelow " + Math.Round((double)((orderedList.Percentile <double>(99M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); Console.WriteLine("99.9%\tbelow " + Math.Round((double)((orderedList.Percentile <double>(99.9M) * 1000.0) / ((double)Stopwatch.Frequency))) + "ms"); Thread.Sleep(500); logSourece.Cancel(); Thread.Sleep(500); writer.Flush(); } catch (Exception exception) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(exception); } Console.ResetColor(); }
private void RequestRiverBedHomePageAsync( IMethodLogger logger, int numberOfRequestsToMake) { var requestTimes = new ConcurrentBag<long>(); int htmlLength = 0; try { var tasks = Enumerable.Range(0, numberOfRequestsToMake) .Select(async x => { var requestStopWatch = Stopwatch.StartNew(); var webClient = new WebClient(); using (var stream = await webClient.OpenReadTaskAsync(new Uri("http://www.riverbed.com"))) using (var sr = new StreamReader(stream)) { var html = await sr.ReadToEndAsync(); htmlLength = html.Length; } requestTimes.Add(requestStopWatch.ElapsedMilliseconds); }); Task.WaitAll(tasks.ToArray()); } catch (Exception e) { throw new Exception("Error getting http://www.riverbed.com: " + e.Message + Environment.NewLine + e.StackTrace); } logger.WriteMethodInfo( string.Format("Html Length [{0:n0}] chars. Request Times: Min [{1:n0}] Avg [{2:n0}] Max [{3:n0}]", htmlLength, requestTimes.Min(), requestTimes.Average(), requestTimes.Max())); logger.WriteMethodInfo(""); }
private async Task StartSimulation() { if(Simulator.SongData==null) { MessageBox.Show("楽曲を選んでください"); return; } if (Simulator.Unit == null) { MessageBox.Show("ユニットを選んでください"); return; } if (Runs < 1 || Runs > 1000000) { MessageBox.Show("試行回数は1から1,000,000までである必要があります"); return; } Note[] pattern = null; if (UtilizeActualPattern) { pattern = await new PatternProvider().GetPattern(Simulator.Song, Simulator.SongData.Difficulty, Simulator.SongData.Notes); if (pattern == null) { MessageBox.Show($"{Simulator.Song.Title}({Simulator.SongData.Difficulty})の譜面データが見つかりませんでした。"); return; } } SimulationCompleted = false; var results = new ConcurrentBag<SimulationResult>(); await Task.Run(() => Parallel.For(1, Runs+1, i => results.Add(Simulator.StartSimulation(RandomFactory.Create(), i, pattern == null ? null : new Queue<Note>(pattern))))); MaxScore = results.Max(x=>x.Score); MaxScorePerNote = results.Max(x => x.ScorePerNote); MinScore = results.Min(x => x.Score); MinScorePerNote = results.Min(x => x.ScorePerNote); AverageScore = (int)results.Average(x => x.Score); AverageScorePerNote = (int)results.Average(x => x.ScorePerNote); ScoreDistribution = results.GroupBy(x => (int)Math.Floor(x.Score / 10000.0)).OrderBy(x => x.Key).ToDictionary(x => x.Key, x => (double)x.Count() / results.Count); StandardDeviation = Math.Round(Math.Sqrt(results.Sum(x => Math.Pow(x.Score - AverageScore, 2))) / results.Count); int idx = 1; var duration = results.First().Duration; ActualTriggerRatio = Simulator.Unit.Slots.ToDictionary(s => $"スロット{idx++}", s => s == null ? 0 : results.SelectMany(x => x.TriggeredSkills).Where(x => x.Who == s).Count() / (results.Count * Math.Floor((duration - 1.0) / s.Skill.Interval))); SimulationResults = results.OrderBy(x => x.Id).Take(100).ToList(); SelectedResult = SimulationResults[0]; SimulationCompleted = true; }
private async Task StartSimulation() { if(Simulator.SongData==null) { MessageBox.Show("楽曲を選んでください"); return; } if (Simulator.Unit == null) { MessageBox.Show("ユニットを選んでください"); return; } var results = new ConcurrentBag<SimulationResult>(); await Task.Run(() => Parallel.For(1, 101, i => results.Add(Simulator.StartSimulation(RandomFactory.Create(), i)))); MaxScore = results.Max(x=>x.Score); MaxScorePerNote = results.Max(x => x.ScorePerNote); MinScore = results.Min(x => x.Score); MinScorePerNote = results.Min(x => x.ScorePerNote); AverageScore = (int)results.Average(x => x.Score); AverageScorePerNote = (int)results.Average(x => x.ScorePerNote); SimulationResults = results.OrderBy(x => x.Id).ToList(); SelectedResult = SimulationResults[0]; }
static async Task Main(string[] args) { // 测试1000次调用 var test = new Test(1000); #region 循环调用 var listGrpc = new List <long>(); await test.TestGrpc(listGrpc); var listGrpcSingleConnection = new List <long>(); await test.TestGrpcSingleConnection(listGrpcSingleConnection); var listGrpcConsoleApp = new List <long>(); await test.TestGrpcConsoleApp(listGrpcConsoleApp); var listGrpcConsoleAppSingleConnection = new List <long>(); await test.TestGrpcConsoleAppSingleConnection(listGrpcConsoleAppSingleConnection); var listWebApi = new List <long>(); await test.TestWebApi(listWebApi); var listWebApiSingleConnection = new List <long>(); await test.TestWebApiSingleConnection(listWebApiSingleConnection); Console.WriteLine("***** TEST RESULT gRPC Grpc.AspNetCore *****"); Console.WriteLine("min:" + listGrpc.Min()); Console.WriteLine("max:" + listGrpc.Max()); Console.WriteLine("avg:" + listGrpc.Average()); Console.WriteLine("***** TEST RESULT gRPC ConsoleApp *****"); Console.WriteLine("min:" + listGrpcConsoleApp.Min()); Console.WriteLine("max:" + listGrpcConsoleApp.Max()); Console.WriteLine("avg:" + listGrpcConsoleApp.Average()); Console.WriteLine("***** TEST RESULT WebApi *****"); Console.WriteLine("min:" + listWebApi.Min()); Console.WriteLine("max:" + listWebApi.Max()); Console.WriteLine("avg:" + listWebApi.Average()); Console.WriteLine("***** TEST RESULT gRPC SingleConnection Grpc.AspNetCore *****"); Console.WriteLine("min:" + listGrpcSingleConnection.Min()); Console.WriteLine("max:" + listGrpcSingleConnection.Max()); Console.WriteLine("avg:" + listGrpcSingleConnection.Average()); Console.WriteLine("***** TEST RESULT gRPC ConsoleApp SingleConnection *****"); Console.WriteLine("min:" + listGrpcConsoleAppSingleConnection.Min()); Console.WriteLine("max:" + listGrpcConsoleAppSingleConnection.Max()); Console.WriteLine("avg:" + listGrpcConsoleAppSingleConnection.Average()); Console.WriteLine("***** TEST RESULT WebApi SingleConnection *****"); Console.WriteLine("min:" + listWebApiSingleConnection.Min()); Console.WriteLine("max:" + listWebApiSingleConnection.Max()); Console.WriteLine("avg:" + listWebApiSingleConnection.Average()); #endregion #region 并发调用 var listGrpcConcurrency = new ConcurrentBag <long>(); await test.TestGrpcConcurrency(listGrpcConcurrency); var listGrpcConsoleAppConcurrency = new ConcurrentBag <long>(); await test.TestGrpcConsoleAppConcurrency(listGrpcConsoleAppConcurrency); var listWebApiConcurrency = new ConcurrentBag <long>(); await test.TestWebApiConcurrency(listWebApiConcurrency); Console.WriteLine("Show result(Y/N):"); var showResult = Console.ReadLine(); while (showResult.Equals("y", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("***** TEST RESULT gRPC Concurrency Grpc.AspNetCore *****"); Console.WriteLine("count:" + listGrpcConcurrency.Count); if (listGrpcConcurrency.Count > 0) { Console.WriteLine("min:" + listGrpcConcurrency.Min()); Console.WriteLine("max:" + listGrpcConcurrency.Max()); Console.WriteLine("avg:" + listGrpcConcurrency.Average()); } Console.WriteLine("***** TEST RESULT gRPC ConsoleApp Concurrency *****"); Console.WriteLine("count:" + listGrpcConsoleAppConcurrency.Count); if (listGrpcConsoleAppConcurrency.Count > 0) { Console.WriteLine("min:" + listGrpcConsoleAppConcurrency.Min()); Console.WriteLine("max:" + listGrpcConsoleAppConcurrency.Max()); Console.WriteLine("avg:" + listGrpcConsoleAppConcurrency.Average()); } Console.WriteLine("***** TEST RESULT WebApi Concurrency *****"); Console.WriteLine("count:" + listWebApiConcurrency.Count); if (listWebApiConcurrency.Count > 0) { Console.WriteLine("min:" + listWebApiConcurrency.Min()); Console.WriteLine("max:" + listWebApiConcurrency.Max()); Console.WriteLine("avg:" + listWebApiConcurrency.Average()); } Console.WriteLine("Show result(Y/N):"); showResult = Console.ReadLine(); } #endregion Console.ReadKey(); }