本文整理汇总了C#中ConcurrentBag.GroupBy方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentBag.GroupBy方法的具体用法?C# ConcurrentBag.GroupBy怎么用?C# ConcurrentBag.GroupBy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConcurrentBag
的用法示例。
在下文中一共展示了ConcurrentBag.GroupBy方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GroupCall
/// <summary>
/// make a call to a group of phone numbers
/// </summary>
/// <param name="sentFrom">list of phone numbers to call</param>
/// <param name="contentId">database ID of the message to sent</param>
/// <returns>returns a summary of message sent</returns>
public string GroupCall(string sentFrom, IEnumerable<string> receipientPhoneNbrs, string contentId)
{
var statuses = new ConcurrentBag<string>();
Parallel.ForEach(receipientPhoneNbrs, (phone) =>
{
var result = CallPhoneNumber(sentFrom, phone, contentId);
statuses.Add(result);
});
var finalResult = string.Join(Environment.NewLine, statuses.GroupBy(c => c)
.Select(c => $"{c.Count()} were sent with a status of {c.Key}"));
return finalResult;
}
示例2: GetDetails
public IEnumerable<ExternalIssueDetails> GetDetails(IEnumerable<Issue> issues)
{
int ignoredOut;
var tfsIssues = issues.Where(i => IsTfsUrl(i.Url) && int.TryParse(i.Id, out ignoredOut)).ToList();
var queriedIssues = new ConcurrentBag<ExternalIssueDetails>();
Parallel.ForEach(tfsIssues, issue => queriedIssues.Add(GetDetails(issue)));
return queriedIssues
.GroupBy(issue => issue.Id)
.Select(g =>
{
var issue = g.First();
issue.SubIssues = g.SelectMany(i => i.SubIssues).ToList();
return issue;
})
.ToList();
}
示例3: AssertCreateView
public void AssertCreateView(IConnectionPool pool)
{
/**
* Here we have setup a static connection pool seeded with 10 nodes. We force randomization OnStartup to false
* so that we can test the nodes being returned are int the order we expect them to.
* So what order we expect? Imagine the following:
*
* Thread A calls GetNext first without a local cursor and takes the current from the internal global cursor which is 0.
* Thread B calls GetNext() second without a local cursor and therefor starts at 1.
* After this each thread should walk the nodes in successive order using their local cursor
* e.g Thread A might get 0,1,2,3,5 and thread B will get 1,2,3,4,0.
*/
var startingPositions = Enumerable.Range(0, NumberOfNodes)
.Select(i => pool.CreateView().First())
.Select(n => n.Uri.Port)
.ToList();
var expectedOrder = Enumerable.Range(9200, NumberOfNodes);
startingPositions.Should().ContainInOrder(expectedOrder);
/**
* What the above code just proved is that each call to GetNext(null) gets assigned the next available node.
*
* Lets up the ante:
* - call get next over `NumberOfNodes * 2` threads
* - on each thread call getnext `NumberOfNodes * 10` times using a local cursor.
* We'll validate that each thread sees all the nodes and they they wrap over e.g after node 9209
* comes 9200 again
*/
var threadedStartPositions = new ConcurrentBag<int>();
var threads = Enumerable.Range(0, 20)
.Select(i => CreateThreadCallingGetNext(pool, threadedStartPositions))
.ToList();
foreach (var t in threads) t.Start();
foreach (var t in threads) t.Join();
/**
* Each thread reported the first node it started off lets make sure we see each node twice as the first node
* because we started `NumberOfNodes * 2` threads
*/
var grouped = threadedStartPositions.GroupBy(p => p).ToList();
grouped.Count().Should().Be(NumberOfNodes);
grouped.Select(p => p.Count()).Should().OnlyContain(p => p == 2);
}
示例4: 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;
}
示例5: Generate
/// <summary>
/// Applies the loaded templates to <paramref name="templateData"/>.
/// </summary>
/// <param name="templateData">
/// Instance of <see cref="TemplateData"/> containing the various input data needed.
/// </param>
public virtual TemplateOutput Generate(TemplateData templateData)
{
Stopwatch timer = Stopwatch.StartNew();
this._fileResolver.Clear();
ParsedTemplate tmpl = this.PrepareTemplate(templateData);
// collect all work that has to be done
List<UnitOfWork> work = new List<UnitOfWork>();
// resource work units
work.AddRange(this.DiscoverWork(templateData, tmpl.Parameters, tmpl.Resources));
// stylesheet work units
{
List<StylesheetApplication> stylesheetApplications = new List<StylesheetApplication>();
foreach (Stylesheet stylesheet in tmpl.Stylesheets)
{
stylesheetApplications.AddRange(this.DiscoverWork(templateData, tmpl.Parameters, stylesheet));
}
var duplicates =
stylesheetApplications.GroupBy(sa => sa.SaveAs, StringComparer.OrdinalIgnoreCase)
.Where(g => g.Count() > 1);
foreach (var group in duplicates)
{
TraceSources.TemplateSource.TraceError("Duplicate work unit target ({0}) generated from: {1}",
group.Key,
string.Join(", ",
group.Select(sa => '\'' + sa.StylesheetName + '\'')));
foreach (var workunit in group.Skip(1))
{
stylesheetApplications.Remove(workunit);
}
}
work.AddRange(stylesheetApplications);
}
TraceSources.TemplateSource.TraceInformation("Generating {0:N0} documents from {1:N0} stylesheets.",
work.Count, tmpl.Stylesheets.Length);
ConcurrentBag<WorkUnitResult> results = new ConcurrentBag<WorkUnitResult>();
// create context
ITemplatingContext context = new TemplatingContext(this._cache,
this._container,
templateData.OutputFileProvider, // TODO fix this (this._basePath)
templateData,
this._resolvers,
this._templateInfo.Source);
// fill indices
using (TraceSources.TemplateSource.TraceActivity("Indexing input document"))
{
var customXsltContext = CreateCustomXsltContext(templateData.IgnoredVersionComponent);
foreach (var index in tmpl.Indices)
{
TraceSources.TemplateSource.TraceVerbose("Adding index {0} (match: '{1}', key: '{1}')",
index.Name,
index.MatchExpr,
index.KeyExpr);
context.DocumentIndex.AddKey(index.Name, index.MatchExpr, index.KeyExpr, customXsltContext);
}
TraceSources.TemplateSource.TraceInformation("Indexing...");
context.DocumentIndex.BuildIndexes();
}
int totalCount = work.Count;
long lastProgress = Stopwatch.GetTimestamp();
int processed = 0;
// process all units of work
ParallelOptions parallelOptions = new ParallelOptions
{
//MaxDegreeOfParallelism = 1
};
IEnumerable<UnitOfWork> unitsOfWork = work;
if (templateData.Filter != null)
{
unitsOfWork = unitsOfWork
.Where(uow =>
{
if (templateData.Filter(uow))
return true;
TraceSources.TemplateSource.TraceInformation("Filtered unit of work: [{0}] {1}",
//.........这里部分代码省略.........
示例6: DCAwareRoundRobinPolicyCachesLocalNodes
public void DCAwareRoundRobinPolicyCachesLocalNodes()
{
var hostList = new List<Host>
{
TestHelper.CreateHost("0.0.0.1", "dc1"),
TestHelper.CreateHost("0.0.0.2", "dc2"),
TestHelper.CreateHost("0.0.0.3", "dc1"),
TestHelper.CreateHost("0.0.0.4", "dc2"),
TestHelper.CreateHost("0.0.0.5", "dc1"),
TestHelper.CreateHost("0.0.0.6", "dc2"),
TestHelper.CreateHost("0.0.0.7", "dc1"),
TestHelper.CreateHost("0.0.0.8", "dc2"),
TestHelper.CreateHost("0.0.0.9", "dc1"),
TestHelper.CreateHost("0.0.0.10", "dc2")
};
const string localDc = "dc1";
var clusterMock = new Mock<ICluster>();
clusterMock
.Setup(c => c.AllHosts())
.Returns(hostList);
//Initialize the balancing policy
var policy = new DCAwareRoundRobinPolicy(localDc, 1);
policy.Initialize(clusterMock.Object);
var instances = new ConcurrentBag<object>();
Action action = () => instances.Add(policy.GetHosts());
TestHelper.ParallelInvoke(action, 100);
Assert.AreEqual(1, instances.GroupBy(i => i.GetHashCode()).Count());
}
示例7: Search
internal static void Search(string folder)
{
var hoods = new ConcurrentBag<string>();
Parallel.ForEach(Directory.EnumerateFiles(Path.Combine(folder, "tweets")), f =>
{
using (var fs = new FileStream(f, FileMode.Open))
{
var buf = new byte[BufSize];
var bufOffset = 0; // offset into the buffer of the chunk currently read (0 or BufSize / 2)
var start = 0; // offset into the buffer where the current field started
var cur = 0; // number of bytes in current field
var field = 0; // field number
var hoodStart = 0; // offset into the buffer where the hood field started
var hoodCount = 0; // number of bytes in hood field
for (;;)
{
var read = fs.Read(buf, bufOffset, BufSize / 2);
if (read == 0) break;
for (var i = 0; i < read; i++, cur++)
{
var b = buf[bufOffset + i];
if (b == '\t' || b == '\n')
{
if (field == 1)
{
hoodStart = start;
hoodCount = cur - 1;
}
else if (field == 3)
{
if (NaiveSearch(buf, start, start + cur))
{
var hood = (hoodStart + hoodCount) <= BufSize ?
Encoding.UTF8.GetString(buf, hoodStart, hoodCount) :
Encoding.UTF8.GetString(buf, hoodStart, BufSize - hoodStart)
+ Encoding.UTF8.GetString(buf, 0, (hoodStart + hoodCount) - BufSize);
hoods.Add(hood);
}
}
start = bufOffset + i + 1;
cur = 0;
field = (field + 1) % 4;
}
}
bufOffset = (bufOffset + BufSize / 2) % BufSize;
}
}
});
var counts = hoods.GroupBy(t => t)
.OrderByDescending(g => g.Count())
.ThenBy(g => g.Key)
.Select(h => $"{h.Key}\t{h.Count()}");
File.WriteAllLines(Path.Combine(folder, "cs_binary_output"), counts);
}
示例8: Main
static void Main(string[] args)
{
Console.WriteLine("Crank v{0}", typeof(Program).Assembly.GetName().Version);
if (args.Length < 2)
{
Console.WriteLine("Usage: crank [url] [numclients] <batchSize> <batchInterval>");
return;
}
ServicePointManager.DefaultConnectionLimit = Int32.MaxValue;
string url = args[0];
int clients = Int32.Parse(args[1]);
int batchSize = args.Length < 3 ? 50 : Int32.Parse(args[2]);
int batchInterval = args.Length < 4 ? 500 : Int32.Parse(args[3]);
// Increase the number of min threads in the threadpool
ThreadPool.SetMinThreads(clients, 2);
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
var connections = new ConcurrentBag<Connection>();
var totalRunStopwatch = Stopwatch.StartNew();
Task.Run(async () =>
{
Console.WriteLine("Ramping up connections. Batch size {0}.", batchSize);
var rampupStopwatch = Stopwatch.StartNew();
await ConnectBatches(url, clients, batchSize, batchInterval, connections);
Console.WriteLine("Started {0} connection(s).", connections.Count);
Console.WriteLine("Setting up event handlers");
rampupStopwatch.Stop();
Console.WriteLine("Ramp up complete in {0}.", rampupStopwatch.Elapsed);
});
Console.WriteLine("Press 'q' to quit.");
while (true)
{
var keyInfo = Console.ReadKey(intercept: true);
if (keyInfo.Key == ConsoleKey.Q)
{
break;
}
Console.WriteLine("Total Running time: {0}", totalRunStopwatch.Elapsed);
Console.WriteLine("End point: {0}", url);
Console.WriteLine("Total connections: {0}", clients);
foreach (var g in connections.GroupBy(c => c.State))
{
Console.WriteLine(g.Key + " connections: {0}", g.Count());
}
foreach (var g in connections.GroupBy(c => c.Transport.Name))
{
Console.WriteLine(g.Key + " connections: {0}", g.Count());
}
}
totalRunStopwatch.Stop();
_running = false;
Console.WriteLine("Closing connection(s).");
Parallel.ForEach(connections, connection => connection.Stop());
}
示例9: Generate
/// <summary>
/// Applies the loaded templates to <paramref name="templateData"/>.
/// </summary>
/// <param name="templateData">
/// Instance of <see cref="TemplateData"/> containing the various input data needed.
/// </param>
public virtual TemplateOutput Generate(TemplateData templateData)
{
Stopwatch timer = Stopwatch.StartNew();
ParsedTemplate tmpl = this.PrepareTemplate(templateData);
// collect all work that has to be done
List<UnitOfWork> work = new List<UnitOfWork>();
// resource work units
work.AddRange(this.DiscoverWork(templateData, tmpl.Resources));
// stylesheet work units
{
List<StylesheetApplication> stylesheetApplications = new List<StylesheetApplication>();
foreach (Stylesheet stylesheet in tmpl.Stylesheets)
{
stylesheetApplications.AddRange(this.DiscoverWork(templateData, stylesheet));
}
var duplicates =
stylesheetApplications.GroupBy(sa => sa.SaveAs, StringComparer.OrdinalIgnoreCase)
.Where(g => g.Count() > 1);
foreach (var group in duplicates)
{
TraceSources.TemplateSource.TraceError("Duplicate work unit target ({0}) generated from: {1}",
group.Key,
string.Join(", ",
group.Select(sa => '\'' + sa.StylesheetName + '\'')));
foreach (var workunit in group.Skip(1))
{
stylesheetApplications.Remove(workunit);
}
}
work.AddRange(stylesheetApplications);
}
TraceSources.TemplateSource.TraceInformation("Generating {0:N0} documents from {1:N0} stylesheets.",
work.Count, tmpl.Stylesheets.Length);
ConcurrentBag<WorkUnitResult> results = new ConcurrentBag<WorkUnitResult>();
// create context
ITemplatingContext context = new TemplatingContext(this._cache,
this._basePath,
templateData,
this._resolvers,
this._fileProvider);
// fill indices
using (TraceSources.TemplateSource.TraceActivity("Indexing input document"))
{
var customXsltContext = CreateCustomXsltContext(templateData.IgnoredVersionComponent);
foreach (var index in tmpl.Indices)
{
TraceSources.TemplateSource.TraceVerbose("Adding index {0} (match: '{1}', key: '{1}')",
index.Name,
index.MatchExpr,
index.KeyExpr);
context.DocumentIndex.AddKey(index.Name, index.MatchExpr, index.KeyExpr, customXsltContext);
}
TraceSources.TemplateSource.TraceInformation("Indexing...");
context.DocumentIndex.BuildIndexes();
}
int totalCount = work.Count;
long lastProgress = Stopwatch.GetTimestamp();
int processed = 0;
// process all units of work
ParallelOptions parallelOptions = new ParallelOptions
{
//MaxDegreeOfParallelism = 1
};
Parallel.ForEach(work,
parallelOptions,
uow =>
{
results.Add(uow.Execute(context));
int c = Interlocked.Increment(ref processed);
long lp = Interlocked.Read(ref lastProgress);
if ((Stopwatch.GetTimestamp() - lp) / (double)Stopwatch.Frequency > 5.0)
{
if (Interlocked.CompareExchange(ref lastProgress,
Stopwatch.GetTimestamp(),
lp) == lp)
{
TraceSources.TemplateSource.TraceInformation(
//.........这里部分代码省略.........
示例10: Generate
/// <summary>
/// Applies the loaded templates to <paramref name="templateData"/>.
/// </summary>
/// <param name="templateData">
/// Instance of <see cref="TemplateData"/> containing the various input data needed.
/// </param>
public virtual TemplateOutput Generate(TemplateData templateData)
{
Stopwatch timer = Stopwatch.StartNew();
ParsedTemplate tmpl = this.PrepareTemplate(templateData);
// collect all work that has to be done
List<UnitOfWork> work = new List<UnitOfWork>();
// resource work units
work.AddRange(this.DiscoverWork(templateData, tmpl.Resources));
// stylesheet work units
{
List<StylesheetApplication> stylesheetApplications = new List<StylesheetApplication>();
foreach (Stylesheet stylesheet in tmpl.Stylesheets)
{
stylesheetApplications.AddRange(this.DiscoverWork(templateData, stylesheet));
}
var duplicates =
stylesheetApplications.GroupBy(sa => sa.SaveAs, StringComparer.OrdinalIgnoreCase)
.Where(g => g.Count() > 1);
foreach (var group in duplicates)
{
TraceSources.TemplateSource.TraceCritical("Duplicate work unit target ({0}) generated from: {1}",
group.Key,
string.Join(", ",
group.Select(
sa => '\'' + sa.StylesheetName + '\'')));
// TODO replace this with something more specific
// throw new Exception("Critical error, continuing is not safe.");
}
work.AddRange(stylesheetApplications);
}
TraceSources.TemplateSource.TraceInformation("Generating {0:N0} documents from {1:N0} stylesheets.",
work.Count, tmpl.Stylesheets.Length);
ConcurrentBag<WorkUnitResult> results = new ConcurrentBag<WorkUnitResult>();
// create context
ITemplatingContext context = new TemplatingContext(this._basePath,
templateData,
this._resolvers,
this._fileProvider);
// process all units of work
Parallel.ForEach(work, uow => results.Add(uow.Execute(context)));
// stop timing
timer.Stop();
// prepare stats
Dictionary<Type, WorkUnitResult[]> resultGroups =
results.GroupBy(ps => ps.WorkUnit.GetType()).ToDictionary(g => g.Key, g => g.ToArray());
var stylesheetStats =
resultGroups[typeof(StylesheetApplication)]
.GroupBy(r => ((StylesheetApplication)r.WorkUnit).StylesheetName);
foreach (var statGroup in stylesheetStats)
{
TraceSources.TemplateSource.TraceInformation("Applied stylesheet '{0}' {1:N0} times in {2:N0} ms (min: {3:N0}, mean {4:N0}, max {5:N0}, avg: {6:N0})",
statGroup.Key,
statGroup.Count(),
statGroup.Sum(ps => ps.Duration) / 1000.0,
statGroup.Min(ps => ps.Duration) / 1000.0,
statGroup.Skip(statGroup.Count() / 2).Take(1).Single().Duration / 1000.0,
statGroup.Max(ps => ps.Duration) / 1000.0,
statGroup.Average(ps => ps.Duration) / 1000.0);
}
var resourceStats = resultGroups[typeof(ResourceDeployment)];
foreach (var statGroup in resourceStats)
{
TraceSources.TemplateSource.TraceInformation("Deployed resource '{0}' in {1:N0} ms",
((ResourceDeployment)statGroup.WorkUnit).ResourcePath,
statGroup.Duration);
}
TraceSources.TemplateSource.TraceInformation("Documentation generated in {0:N1} seconds (processing time: {1:N1} seconds)",
timer.Elapsed.TotalSeconds,
results.Sum(ps => ps.Duration) / 1000000.0);
return new TemplateOutput(results.ToArray());
//.........这里部分代码省略.........
示例11: PrintResults
private static void PrintResults(int itemsToStore, ConcurrentBag<Stopwatch> individualTimings, Stopwatch stopwatch, int totalSize)
{
Console.WriteLine("Elapsed: " + stopwatch.Elapsed);
Console.WriteLine("Bytes: " + totalSize / 1024 / 1024 + "MB");
// redis style
int runningTotal = 0;
foreach (var timingGroup in individualTimings
.GroupBy(x => x.ElapsedMilliseconds <= 10 ? x.ElapsedMilliseconds : ((int)(x.ElapsedMilliseconds / 10)) * 10 + 10) // normalize to 10 second intervals, rounded up
.OrderBy(x => x.Key))
{
runningTotal += timingGroup.Count();
Console.WriteLine("{0}% <= {1} milliseconds", runningTotal / (double)itemsToStore * 100, timingGroup.Key);
}
}
示例12: 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();
}
示例13: RoundRobinShouldEvenlyDistributeAcrossManyPartitions
public void RoundRobinShouldEvenlyDistributeAcrossManyPartitions()
{
const int TotalPartitions = 100;
var selector = new DefaultPartitionSelector();
var partitions = new List<Partition>();
for (int i = 0; i < TotalPartitions; i++)
{
partitions.Add(new Partition { LeaderId = i, PartitionId = i });
}
var topic = new Topic { Name = "a", Partitions = partitions };
var bag = new ConcurrentBag<Partition>();
Parallel.For(0, TotalPartitions * 3, x => bag.Add(selector.Select(topic, null)));
var eachPartitionHasThree = bag.GroupBy(x => x.PartitionId).Count();
Assert.That(eachPartitionHasThree, Is.EqualTo(TotalPartitions), "Each partition should have received three selections.");
}