public void CheckReadPerformance(int numberOfEvents) { var stopwatch = Stopwatch.StartNew(); WriteEvents(numberOfEvents); var seconds = stopwatch.Elapsed.TotalSeconds; Console.WriteLine("Writing {0} events took {1:0.0} s - that's {2:0.0} events/s", numberOfEvents, seconds, numberOfEvents / seconds); var measuredSeconds = new List<Tuple<double, int>>(); 100.Times(() => { var readStopwatch = Stopwatch.StartNew(); var randomAggregateRootId = GetRandomAggregateRootId(); var events = _eventStore.Load(randomAggregateRootId).ToList(); measuredSeconds.Add(Tuple.Create(readStopwatch.Elapsed.TotalSeconds, events.Count)); }); Console.WriteLine("Reading entire root event stream took {0:0.0} for {1:0.0} events - that's {2:0.0} events/s (AVG)", measuredSeconds.Average(a => a.Item1), measuredSeconds.Average(a => a.Item2), measuredSeconds.Average(a => a.Item2)/measuredSeconds.Average(a => a.Item1)); var streamStopwatch = Stopwatch.StartNew(); var counter = 0; foreach (var e in _eventStore.Stream()) { counter++; } var totalSeconds = streamStopwatch.Elapsed.TotalSeconds; Console.WriteLine("Streaming all events took {0:0.0} s for {1} events - that's {2:0.0} events/s", totalSeconds, counter, counter/ totalSeconds); }
public void Can_get_few_records_test() { var efDriver = new EFDriver(); var times = new List<double>(); for (int i = 0; i < 100; ++i) { var sw = Stopwatch.StartNew(); var rows = efDriver.GetAFewRecords(); Assert.That(rows, Is.Not.Null); Assert.That(rows.Count(), Is.GreaterThan(0)); sw.Stop(); times.Add(sw.ElapsedMilliseconds); Console.WriteLine("took {0} ms to get {1} records", sw.ElapsedMilliseconds, rows.Count()); } Console.WriteLine("average: {0}, min: {1}, max: {2}, std dev: {3}, median: {4}", times.Average(), times.Min(), times.Max(), times.StandardDeviation(), times.Median()); var timesSansMinAndMax = new List<double>(); timesSansMinAndMax.AddRange(times); timesSansMinAndMax.Remove(timesSansMinAndMax.Min()); timesSansMinAndMax.Remove(timesSansMinAndMax.Max()); Console.WriteLine("average sans min & max: {0}", timesSansMinAndMax.Average()); }
public void Can_get_lots_of_records_with_new_instantiation_every_time_test() { var times = new List<double>(); for (int i = 0; i < 40; ++i) { var sw = Stopwatch.StartNew(); var dapperDriver = new DapperDriver(); var rows = dapperDriver.GetLotsOfRecords<TransactionHistory>(); Assert.That(rows, Is.Not.Null); Assert.That(rows.Count(), Is.GreaterThan(0)); sw.Stop(); times.Add(sw.ElapsedMilliseconds); Console.WriteLine("took {0} ms to get {1} records", sw.ElapsedMilliseconds, rows.Count()); } Console.WriteLine("average: {0}, min: {1}, max: {2}", times.Average(), times.Min(), times.Max()); var timesSansMinAndMax = new List<double>(); timesSansMinAndMax.AddRange(times); timesSansMinAndMax.Remove(timesSansMinAndMax.Min()); timesSansMinAndMax.Remove(timesSansMinAndMax.Max()); Console.WriteLine("average sans min & max: {0}", timesSansMinAndMax.Average()); }
public void Should38() { var times = new List<long>(); var lines = File.ReadAllLines("C:\\tmp\\badphonenumber-clean.log"); foreach (var line in lines) { var stopwatch = new Stopwatch(); stopwatch.Start(); var isValidNumber = IsValidNumber(line.Trim()); stopwatch.Stop(); if (isValidNumber) { Console.WriteLine("{0}", line); } times.Add(stopwatch.ElapsedMilliseconds); Thread.Sleep(TimeSpan.FromMilliseconds(500)); } var average = times.Average(); var count = times.Count; var sum = times.Sum(); var max = times.Max(); Console.WriteLine("{0} ms. {1} numbers. {2} sum. {3} max", average, count, sum, max); }
public void Should_scale_threads_to_meet_demand() { var now = DateTime.Now; var latency = new List<long>(); for (int i = 0; i < 100; i++) { var timer = Stopwatch.StartNew(); LocalBus.Publish(new A()); Assert.IsTrue(_before.WaitOne(30.Seconds()), "Consumer thread failed to start"); timer.Stop(); latency.Add(timer.ElapsedMilliseconds); } Console.WriteLine("Average latency: {0}ms", latency.Average()); _wait.Set(); for (int i = 0; i < 100; i++) { Assert.IsTrue(_after.WaitOne(30.Seconds()), "Consumer thread failed to complete"); } Console.WriteLine("Elapsed Time: {0}", DateTime.Now - now); }
public void RunTest(bool useLowLatencyBackoffStrategy, int iterations) { var adapter = new BuiltinContainerAdapter(); var messageHasBeenReceived = new ManualResetEvent(false); adapter.Handle<string>(s => messageHasBeenReceived.Set()); ConfigureBus(adapter, useLowLatencyBackoffStrategy); var bus = adapter.Bus; var recordedLatencies = new List<TimeSpan>(); iterations.Times(() => { // let things calm down Console.Write("Calming down.... "); Thread.Sleep(30.Seconds()); Console.Write("Sending! "); var sendTime = DateTime.UtcNow; bus.SendLocal("w0000tamafooook!!1"); Console.Write("waiting... "); messageHasBeenReceived.WaitUntilSetOrDie(20.Seconds()); var elapsedUntilNow = sendTime.ElapsedUntilNow(); Console.WriteLine("got the message - recorded latency of {0}", elapsedUntilNow); recordedLatencies.Add(elapsedUntilNow); messageHasBeenReceived.Reset(); }); Console.WriteLine("AVERAGE RECORDED LATENCY: {0:0.00} s", recordedLatencies.Average(t => t.TotalSeconds)); }
public void Can_get_lots_of_records_with_new_instantiation_every_time_test() { var times = new List<double>(); for (int i = 0; i < 40; ++i) { var sw = Stopwatch.StartNew(); var efDriver = new EFDriver(); var rows = efDriver.GetLotsOfRecords(); Assert.That(rows, Is.Not.Null); Assert.That(rows.Count(), Is.GreaterThan(0)); sw.Stop(); times.Add(sw.ElapsedMilliseconds); Console.WriteLine("took {0} ms to get {1} records", sw.ElapsedMilliseconds, rows.Count()); } Console.WriteLine("average: {0}, min: {1}, max: {2}, std dev: {3}", times.Average(), times.Min(), times.Max(), times.StandardDeviation()); }
public void EmptyArray_NoIndex() { var emptyArry = new int[0]; int x = 0; var list = new List<double>(); //var result = 8 / x; var result = list.Average(); // var result = question.solution(emptyArry); Assert.AreEqual(0, 0); }
public void average_LowerThenMinDouble_returnMinusInf() { List<double> first = new List<double>(); for (int i = 0; i < 5; i++) { first.Add(double.MaxValue * -2); } a.getAverageValue(first); Assert.AreEqual(Double.NegativeInfinity, first.Average()); }
public void average_MoreThenMaxDouble_returnInf() { List<double> first = new List<double>(); for (int i = 0; i < 5; i++) { first.Add(double.MaxValue*2); } a.getAverageValue(first); Assert.AreEqual(Double.PositiveInfinity, first.Average()); }
public void average_NormalPositiveValues_returnCorrectValue() { List<double> first = new List<double>(); for(int i = 0; i < 5; i++) { first.Add(i * 10); } double expected = 20.0; a.getAverageValue(first); Assert.AreEqual(expected, first.Average()); }
public void getting_stack_overflow() { var l = new List<Stopwatch>(); for (var i = 0; i < 10000; i++) { var w = Stopwatch.StartNew(); PathInfo.Parse("C:"); w.Stop(); l.Add(w); } Console.WriteLine("mean time: {0}", l.Average(x => x.ElapsedTicks)); }
private static void DumpHistory(List<EodPoint> download) { Console.WriteLine("Assert.AreEqual({0}, download.Count);", download.Count); Console.WriteLine("Assert.IsTrue(download.All(x => x.High >= x.Low));"); Console.WriteLine("Assert.AreEqual({0}m, download.Average(x => x.{1}));", download.Average(x => x.Adj_Close).ToString(CultureInfo.InvariantCulture), "Adj_Close"); Console.WriteLine("Assert.AreEqual({0}m, download.Average(x => x.{1}));", download.Average(x => x.Close).ToString(CultureInfo.InvariantCulture), "Close"); Console.WriteLine("Assert.AreEqual({0}m, download.Average(x => x.{1}));", download.Average(x => x.High).ToString(CultureInfo.InvariantCulture), "High"); Console.WriteLine("Assert.AreEqual({0}m, download.Average(x => x.{1}));", download.Average(x => x.Low).ToString(CultureInfo.InvariantCulture), "Low"); Console.WriteLine("Assert.AreEqual({0}m, download.Average(x => x.{1}));", download.Average(x => x.Open).ToString(CultureInfo.InvariantCulture), "Open"); Console.WriteLine("Assert.AreEqual({0}, download.Average(x => x.{1}), 1);", download.Average(x => x.Volume).ToString(CultureInfo.InvariantCulture), "Volume"); }
public void AnalyseConditionalCopySpeed() { var stopwatch = new Stopwatch(); stopwatch.Start(); var timings = new List<long> { RunConditionalCopy(BuildAndMeasureTree(stopwatch), stopwatch), RunConditionalCopy(BuildAndMeasureTree(stopwatch), stopwatch), RunConditionalCopy(BuildAndMeasureTree(stopwatch), stopwatch), RunConditionalCopy(BuildAndMeasureTree(stopwatch), stopwatch), RunConditionalCopy(BuildAndMeasureTree(stopwatch), stopwatch), RunConditionalCopy(BuildAndMeasureTree(stopwatch), stopwatch), RunConditionalCopy(BuildAndMeasureTree(stopwatch), stopwatch), RunConditionalCopy(BuildAndMeasureTree(stopwatch), stopwatch), }; timings.Average().Should().BeLessOrEqualTo(100); }
public void FilterLargeGraphSpeed() { var stopwatch = new Stopwatch(); stopwatch.Start(); var timings = new List<long> { RunFilter(BuildAndMeasureTree(stopwatch), stopwatch), RunFilter(BuildAndMeasureTree(stopwatch), stopwatch), RunFilter(BuildAndMeasureTree(stopwatch), stopwatch), RunFilter(BuildAndMeasureTree(stopwatch), stopwatch), RunFilter(BuildAndMeasureTree(stopwatch), stopwatch), RunFilter(BuildAndMeasureTree(stopwatch), stopwatch), RunFilter(BuildAndMeasureTree(stopwatch), stopwatch), RunFilter(BuildAndMeasureTree(stopwatch), stopwatch), }; timings.Average().Should().BeLessOrEqualTo(100); }
public void Test() { var text = @"The arts are a vast subdivision of culture, composed of many creative endeavors and disciplines. It is a broader term than ""art"", which as a description of a field usually means only the visual arts. The arts encompass the visual arts, the literary arts and the performing arts – music, theatre, dance and film, among others. This list is by no means comprehensive, but only meant to introduce the concept of the arts. For all intents and purposes, the history of the arts begins with the history of art. The arts might have origins in early human evolutionary prehistory. According to a recent suggestion, several forms of audio and visual arts (rhythmic singing and drumming on external objects, dancing, body and face painting) were developed very early in hominid evolution by the forces of natural selection in order to reach an altered state of consciousness. In this state, which Jordania calls battle trance, hominids and early human were losing their individuality, and were acquiring a new collective identity, where they were not feeling fear or pain, and were religiously dedicated to the group interests, in total disregards of their individual safety and life. This state was needed to defend early hominids from predators, and also to help to obtain food by aggressive scavenging. Ritualistic actions involving heavy rhythmic music, rhythmic drill, coupled sometimes with dance and body painting had been universally used in traditional cultures before the hunting or military sessions in order to put them in a specific altered state of consciousness and raise the morale of participants."; var hyphenator = new Hyphenator(HyphenatePatternsLanguage.EnglishUs, "-"); var stopWatches = new List<long>(); for (int i = 0; i < 200; i++) { var startNew = Stopwatch.StartNew(); hyphenator.HyphenateText(text); startNew.Stop(); if (i > 10) stopWatches.Add(startNew.ElapsedMilliseconds); } var avg = stopWatches.Average(); var disp = stopWatches.Select(x => Math.Abs(avg - x)).Max(); Console.WriteLine("{0} ± {1}",avg,disp); }
public void Determine_tasktimer_accuracy() { var r = new Random(); var deltas = new List<int>(); for(var i = 0; i < 100; i++) { var interval = r.Next(100, 600); var stopwatch = Stopwatch.StartNew(); TaskTimerFactory.Current.New(TimeSpan.FromMilliseconds(interval), tt => { stopwatch.Stop(); var delta = stopwatch.ElapsedMilliseconds - interval; double avg = 0; lock(deltas) { deltas.Add((int)delta); avg = deltas.Average(); } Console.WriteLine("Expected {0:0}ms was {1:0}ms, delta {2:0}ms, avg {3:0}", interval, stopwatch.ElapsedMilliseconds, delta, avg); }, null, TaskEnv.None); Thread.Sleep(300); } }
public void TestWord() { var hyphenator = new Hyphenator(HyphenatePatternsLanguage.EnglishUs, "-"); var stopWatches = new List<long>(); for (int i = 0; i < 1000; i++) { var startNew = Stopwatch.StartNew(); hyphenator.HyphenateText("subdivision"); hyphenator.HyphenateText("creative"); hyphenator.HyphenateText("disciplines"); startNew.Stop(); if (i > 2) stopWatches.Add(startNew.ElapsedMilliseconds); } var avg = stopWatches.Average(); var disp = stopWatches.Select(x => Math.Abs(avg - x)).Max(); Console.WriteLine("{0} ± {1}", avg, disp); }
public void SpeedTest() { string dsdPath = Utility.GetPath("lib\\StructureSample.xml"); const int smallLoopCount = 1; const int bigLoopCount = 1000; var list = new List<decimal>(); var list2 = new List<TimeSpan>(); for (int i = 0; i < bigLoopCount; i++) { var stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); for (int j = 0; j < smallLoopCount; j++) { using (var reader = XmlReader.Create(dsdPath)) { while (reader.Read()) { } } } stopWatch.Stop(); long ticks = stopWatch.ElapsedTicks; stopWatch.Restart(); for (int k = 0; k < smallLoopCount; k++) { var message = StructureMessage.Load(dsdPath); } stopWatch.Stop(); Console.Write((decimal)stopWatch.ElapsedTicks / ticks); list.Add((decimal)stopWatch.ElapsedTicks / ticks); list2.Add(stopWatch.Elapsed); Console.WriteLine(" : {0}", stopWatch.Elapsed); } Console.WriteLine("Average: {0}", list.Average()); Console.WriteLine("Average Time: {0}", TimeSpan.FromTicks((long)list2.Select(i => i.Ticks).Average())); }
public void GetProcessorUtilizationInPercent_Every10Milliseconds_For5Seconds() { // Arrange int durationInMilliseconds = 5 * 1000; int waitPeriodInMilliseconds = 100; int timeWaited = 0; var values = new List<double>(); // Act using (var processorStatusProvider = new ProcessorStatusProvider()) { do { values.Add(processorStatusProvider.GetProcessorStatus().ProcessorUtilizationInPercent); Thread.Sleep(waitPeriodInMilliseconds); timeWaited += waitPeriodInMilliseconds; } while (timeWaited <= durationInMilliseconds); } // Assert Assert.AreNotEqual(0d, values.Average()); }
/// <summary> /// Calculates the p-value until statistically insignificant or past a number of iterations (100); /// </summary> /// <param name="preDist"></param> /// <param name="postDist"></param> /// <param name="testType"></param> private void TestAlignmentPValueToFailure(List<double> preDist, List<double> postDist, HypothesisTests testType, double step) { double pValue = 0; var nIterations = 0; double shift = 0; Print("Mean-Pre, Mean Post, Shift Amount, Mean Diff, p-Value two, left, right"); var meanPost = postDist.Average(); var postHistogram = new Histogram(.002, -.05, .05, "post-alignment"); postHistogram.AddData(postDist); var histograms = new List<Histogram>(); histograms.Add(postHistogram); while (pValue < .05 && nIterations < 100) { var newPre = new List<double>(); preDist.ForEach(x => newPre.Add(x + shift)); var mean = newPre.Average(); var test = HypothesisTestingFactory.CreateTests(testType); var data = test.Test(newPre, postDist); Print(string.Format("{0},{1},{2},{3},{4},{5},{5}", mean, meanPost, shift, Math.Abs(mean - meanPost), data.TwoTail, data.LeftTail, data.RightTail)); var preHistogram = new Histogram(.002, -.05, .05, string.Format("{0:.0000}", mean)); preHistogram.AddData(newPre); histograms.Add(preHistogram); pValue = data.TwoTail; nIterations++; shift += step; } var originalPreHistogram = new Histogram(.002, -.05, .05, "pre-histogram"); originalPreHistogram.AddData(preDist); Print(""); PrintHistogram(originalPreHistogram); Print(""); PrintHistogram(postHistogram); Print(""); PrintHistogram("pre-post", histograms); Print(""); }
public void HandlesAtLeast10kTicksPerSecondWithTwentySymbols() { // this ran at ~25k ticks/per symbol for 20 symbols var algorithm = new AlgorithmStub(Resolution.Tick, Enumerable.Range(0, 20).Select(x => x.ToString()).ToList()); var t = Enumerable.Range(0, 20).Select(x => new Tick {Symbol = SymbolCache.GetSymbol(x.ToString())}).ToList(); var feed = RunDataFeed(algorithm, handler => t); var flag = false; int ticks = 0; var averages = new List<decimal>(); var timer = new Timer(state => { var avg = ticks/20m; Interlocked.Exchange(ref ticks, 0); Console.WriteLine("Average ticks per symbol: " + avg.SmartRounding()); if (flag) flag = false; averages.Add(avg); }, null, Time.OneSecond, Time.OneSecond); ConsumeBridge(feed, TimeSpan.FromSeconds(5), false, ts => { Interlocked.Add(ref ticks, ts.Slice.Ticks.Sum(x => x.Value.Count)); }, true); var average = averages.Average(); Console.WriteLine("\r\nAverage ticks per symbol per second: " + average); Assert.That(average, Is.GreaterThan(10000)); }
protected void Run(Action whatToRun, string testNameSuffix = "", Action before = null, Action after = null) { before = before ?? new Action(() => {}); after = after ?? new Action(() => {}); var success = false; var tries = 1; var fails = new List<string>(); while(!success) { results = new List<double>(); for(var i = 0; i < WarmUpRounds; i++) { before(); whatToRun(); after(); } while(true) { before(); Measure(whatToRun); after(); if(results.Count >= MinimalNumberOfRuns) { var currentAverage = results.Average(); var currentStdDev = results.StandardDeviation(); results.RemoveAll(x => Math.Abs(x - currentAverage) > 3*currentStdDev); currentStdDev = results.StandardDeviation(); currentAverage = results.Average(); if(currentStdDev/currentAverage <= MinimalRequiredStandardDeviation) { success = true; break; } } if(results.Count > MaximalNumberOfRuns) { fails.Add(string.Format("Maximal number of runs {0} was exceeded, with standard deviation {1:0.00} > {2:0.00}. (Try {3}).", MaximalNumberOfRuns, results.StandardDeviation()/results.Average(), MinimalRequiredStandardDeviation, tries)); break; } } if(tries++ >= MaximalRetriesCount) { Assert.Fail(fails.Aggregate((x, y) => x + Environment.NewLine + y)); } } var average = results.Average(); var stdDev = results.StandardDeviation(); var testName = string.Format("{0}:{1}", TestContext.CurrentContext.Test.Name, testNameSuffix); resultsDb.Append(new Result(testName, average, stdDev, SetUp.TestDate)); File.AppendAllLines(SetUp.TestLogFileName, new [] { string.Format("{0}\t{1}s\t{2:0.00}", testName, average.NormalizeDecimal(), stdDev/average) } ); }
public void BenchSingleAdd() { Database.RegisterDataObject(typeof(TestTable)); Database.RegisterDataObject(typeof(TestTableRelations)); Database.RegisterDataObject(typeof(TestTableRelationsEntries)); Database.DeleteObject(Database.SelectAllObjects<TestTable>()); Database.DeleteObject(Database.SelectAllObjects<TestTableRelations>()); Database.DeleteObject(Database.SelectAllObjects<TestTableRelationsEntries>()); Assert.IsEmpty(Database.SelectAllObjects<TestTable>(), "Database shouldn't have any record For TestTable."); Assert.IsEmpty(Database.SelectAllObjects<TestTableRelations>(), "Database shouldn't have any record For TestTable."); Assert.IsEmpty(Database.SelectAllObjects<TestTableRelationsEntries>(), "Database shouldn't have any record For TestTable."); var objs = Enumerable.Range(0, 100).Select(i => new TestTable { TestField = string.Format("Bench Single Add '{0}'", i) }).ToArray(); var times = new List<long>(); foreach (var obj in objs) { var stopWatch = Stopwatch.StartNew(); Database.AddObject(obj); stopWatch.Stop(); times.Add(stopWatch.ElapsedMilliseconds); } var relationObjs = Enumerable.Range(0, 100).Select(i => new TestTableRelations { TestField = string.Format("Bench Single Relations Add '{0}'", i) }).ToArray(); foreach (var obj in relationObjs) obj.Entries = Enumerable.Range(0, 5).Select(i => new TestTableRelationsEntries { ForeignTestField = obj.ObjectId }).ToArray(); var timesRelations = new List<long>(); foreach (var obj in relationObjs) { var stopWatch = Stopwatch.StartNew(); Database.AddObject(obj); stopWatch.Stop(); timesRelations.Add(stopWatch.ElapsedMilliseconds); } Console.WriteLine("Bench Single TestTable Add Total Elapse {3}ms, Average {0}ms, Min {1}ms, Max {2}ms", times.Average(), times.Min(), times.Max(), times.Sum()); Console.WriteLine("Bench Single TestTableRelations Add Total Elapse {3}ms, Average {0}ms, Min {1}ms, Max {2}ms", timesRelations.Average(), timesRelations.Min(), timesRelations.Max(), timesRelations.Sum()); }
public void ParallelChunkedOneGig(int threadCount) { string path = ""; try { var uri = new Uri(Constants.ONE_GIG_FILE_S_SL); path = SafePath("sites_vcf.gz"); Action<string> logger = (message) => { }; var timer = new Stopwatch(); //a list to hold measured transfer rates var transferRateList = new List<double>(); var asyncProgress = new AsyncProgress<LargeFileDownloadProgressChangedEventArgs>( obj => { transferRateList.Add(obj.DownloadBitRate); logger("progress"); }); var manager = new BufferManager(new[] { new BufferQueueSetting(SimpleHttpGetByRangeClient.BUFFER_SIZE, (uint)threadCount), new BufferQueueSetting(LargeFileDownloadParameters.DEFAULT_MAX_CHUNK_SIZE) }); ILargeFileDownloadParameters parameters = new LargeFileDownloadParameters(uri, path, 1297662912, null, maxThreads: threadCount); timer.Start(); Task task = parameters.DownloadAsync(logger: logger, bufferManager: manager, progress: asyncProgress); task.Wait(TimeSpan.FromMinutes(25)); timer.Stop(); var averageTransferRate = transferRateList.Average(); Debug.WriteLine("Took {0} threads {1} ms with average transfer rate of {2}", threadCount, timer.ElapsedMilliseconds, averageTransferRate); //try to open the file ValidateGZip(path, parameters.FileSize, Constants.ONE_GIG_CHECKSUM); //We expect that the approximate bytes transferred (calculated using average transfer rate) is with maximim error of 30% (accuracy of atleast 70%) Assert.AreEqual(parameters.FileSize, averageTransferRate * timer.Elapsed.TotalSeconds, 0.30 * parameters.FileSize); } finally { File.Delete(path); } }
public void TestLinqAverage2() { var connectionString = _connectionString + "StoreName=" + Guid.NewGuid(); var context = new MyEntityContext(connectionString); var ages = new List<int>(); for (int i = 0; i < 1000; i++) { var entity = context.Entities.Create(); entity.SomeString = "Person" + i; int age = 20 + (i / 20); entity.SomeInt = age; ages.Add(age); } context.SaveChanges(); var total1 = context.Entities.Sum(e => e.SomeInt); var total2 = ages.Sum(); var q1 = context.Entities.Count(); var q2 = ages.Count; Assert.AreEqual(total2 / q2, total1 / q1); Assert.AreEqual(1000, context.Entities.Count()); Assert.AreEqual(ages.Average(), context.Entities.Average(e => e.SomeInt)); }
public void DownloadSmallerFile() { //8 threads //MaxChunkSize = 1048576 //FileSize = 5242880 var uri = new Uri(Constants.FIVE_MEG_FILE); var path = SafePath("sites_vcf.gz"); Action<string> logger = (message) => { }; var transferRateList = new List<double>(); var asyncProgress = new AsyncProgress<LargeFileDownloadProgressChangedEventArgs>( obj => { transferRateList.Add(obj.DownloadBitRate); Debug.WriteLine(obj.DownloadBitRate); logger("progress"); }); var timer = new Stopwatch(); timer.Start(); ILargeFileDownloadParameters parameters = new LargeFileDownloadParameters(uri, path, 1048576, null, maxThreads: 8); Task task = parameters.DownloadAsync(logger: logger, progress:asyncProgress); task.Wait(TimeSpan.FromMinutes(1)); timer.Stop(); var averageTransferRate = transferRateList.Average(); //try to open the file ValidateGZip(path, parameters.FileSize, Constants.FIVE_MEG_CHECKSUM); if (averageTransferRate > 0)// sometimes tx rate is 0, possibly due to caching { Debug.WriteLine("Took {0} threads {1} ms with average transfer rate of {2}", 8, timer.ElapsedMilliseconds, averageTransferRate); //We expect that the approximate bytes transferred (calculated using average transfer rate) is with maximim error of 40% (accuracy of atleast 60%) because it is a small file and txrate is calculated once every two seconds. Assert.GreaterOrEqual(averageTransferRate * timer.Elapsed.TotalSeconds, 0.40 * parameters.FileSize); } }