本文整理汇总了C#中ConcurrentBag.Average方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentBag.Average方法的具体用法?C# ConcurrentBag.Average怎么用?C# ConcurrentBag.Average使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConcurrentBag
的用法示例。
在下文中一共展示了ConcurrentBag.Average方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: MultiThreadPerformanceTest
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));
}
示例2: StartSimulation
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;
}
示例3: StartSimulation
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];
}
示例4: RequestRiverBedHomePageAsync
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("");
}
示例5: RequestRiverBedHomePageMultiThreaded
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("");
}
示例6: Main
//.........这里部分代码省略.........
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();
}