public Task Invoke(HttpContext context) { string name = $"{context.Request.Method} {context.Request.Path}{context.Request.QueryString}"; string uri = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}"; Dictionary <string, string> correlationContext = GetIncomingContext(); //everything happening inside this request will have a proper operation id and //parent activity id set from correlation context using (L.Context(correlationContext)) { using (var time = new TimeMeasure()) { Exception gex = null; try { return(_next(context)); } catch (Exception ex) { gex = ex; throw; } finally { // request will have a new ID but parentId is fetched from current context which links it appropriately using (L.Context(KnownProperty.RequestUri, uri)) { log.Request(name, time.ElapsedTicks, gex); } } } } }
public void ProbaMeasure(double lambda, RrFunction sigma, Duration probaMaturity, Duration simulationMaturity, int quadratureNbPoints, double precision) { var refDate = DateTime.Parse("07/06/2009"); var hw1 = new Hw1Model(TimeMeasure.Act365(refDate), Currency.Eur, lambda, sigma); var probaMeasure = new PaymentInfo(hw1.Currency, refDate + probaMaturity); var t = refDate + simulationMaturity; var hw1PathGen = new Hw1ModelPathGeneratorFactory().Build(hw1, null, probaMeasure, new[] { t }); var brownianBridge = BrownianBridge.Create(hw1PathGen.AllSimulatedDates); var hw1Zc = new Hw1ModelZcRepresentation(hw1); var numeraireZc = hw1Zc.Zc(t, probaMeasure.Date, 1.0); Assert.AreEqual(hw1PathGen.AllSimulatedDates.Length, 1); double[] x, w; GaussHermite.GetQuadrature(quadratureNbPoints, out x, out w); double flow = 0.0; for (int i = 0; i < x.Length; i++) { var dw = brownianBridge.PathIncrements(new[] { x[i] }, 1); var ornstein = hw1PathGen.Path(dw).GetProcessValue(0); flow += w[i] * 1.0 / numeraireZc.Eval(ornstein); } var error = Math.Abs(flow - 1.0); Assert.LessOrEqual(error, precision); }
public StarShip(string name, int?megalightsPerHour, int?consumables, TimeMeasure ConsumablesTimeMeasure) { this.Name = name; this.MegalightsPerHour = megalightsPerHour; this.Consumables = consumables; this.ConsumablesTimeMeasure = ConsumablesTimeMeasure; }
private static void RunTest(string testName, Action <Action <string> > test) { Console.WriteLine("Running {0}", testName); if (!Directory.Exists(_storagePath)) { Directory.CreateDirectory(_storagePath); } TimeMeasure.Start(testName); try { test(message => { TimeMeasure.Stop(testName); WriteInfo($"{TimeMeasure.Result(testName):hh\\:mm\\:ss\\:fff} {message}"); TimeMeasure.Start(testName); }); } finally { TimeMeasure.Stop(testName); Cleanup(); } }
public override async Task OnExecutingAsync(FunctionExecutingContext executingContext, CancellationToken cancellationToken) { Dictionary <string, string> context = GetIncomingContext(); using (L.Context(context)) { using (var time = new TimeMeasure()) { Exception gex = null; try { await base.OnExecutingAsync(executingContext, cancellationToken); } catch (Exception ex) { gex = ex; throw; } finally { using (L.Context( "FunctionName", executingContext.FunctionName, "FunctionInstanceId", executingContext.FunctionInstanceId.ToString())) { if (LogRequests) { log.Request(executingContext.FunctionName, time.ElapsedTicks, gex); } } } } } }
static void Main(string[] args) { L.Config .WriteTo.PoshConsole(); using (var time = new TimeMeasure()) { var ds = new DataSet( new SchemaElement <int>("id"), new SchemaElement <string>("name"), new SchemaElement <double>("lat"), new SchemaElement <double>("lon")); log.Trace(ds.Schema.ToString()); for (int i = 0; i < 10; i++) { ds.Add( i, NameGenerator.GeneratePersonFullName(), Generator.RandomDouble, Generator.RandomDouble); } ParquetWriter.WriteFile(ds, "c:\\tmp\\perf.parquet"); log.Trace("written in {0}", time.Elapsed); } }
private double RotationToPeriod(double rotation, TimeMeasure timeMeasure) { // T = 2Pi / rotation double periodInSeconds = 2 * Math.PI / rotation; switch (timeMeasure) { case TimeMeasure.Second: return(periodInSeconds); case TimeMeasure.Hour: return(periodInSeconds / Constants.Time.Hour_Seconds); case TimeMeasure.Minute: return(periodInSeconds / Constants.Time.Minute_Seconds); case TimeMeasure.Day: return(periodInSeconds / Constants.Time.Day_Seconds); case TimeMeasure.Week: return(periodInSeconds / Constants.Time.Week_Seconds); case TimeMeasure.Month: return(periodInSeconds / Constants.Time.Month_Seconds); case TimeMeasure.Year: return(periodInSeconds / Constants.Time.Year_Seconds); default: return(periodInSeconds); } ; }
static void Main(string[] args) { Console.Title = "DataTanker Performance Tests"; Console.WriteLine("Press Enter to run"); Console.ReadLine(); Console.WriteLine("BPlusTree tests"); BPlusTreeStorageTests.StoragePath = _storagePath; TimeMeasure.Start("Overall"); RunTest("BPlusTree: InsertAndReadMillionRecords", BPlusTreeStorageTests.InsertAndReadMillionRecords); RunTest("BPlusTree: InsertLargeValues", BPlusTreeStorageTests.InsertLargeValues); RunTest("BPlusTree: RandomOperations", BPlusTreeStorageTests.RandomOperations); TimeMeasure.Stop("Overall"); PrintResults(); TimeMeasure.Clear(); Console.WriteLine("RadixTree tests"); RadixTreeStorageTests.StoragePath = _storagePath; TimeMeasure.Start("Overall"); RunTest("RadixTree: EnglishWords", RadixTreeStorageTests.EnglishWords); TimeMeasure.Stop("Overall"); PrintResults(); Console.ReadLine(); }
private static void Basics(int maxObjects) { using (L.Context( "Scenario", "Basics", KnownProperty.OperationId, Guid.NewGuid().ToString())) { using (var time = new TimeMeasure()) { log.Event("Create Started"); for (int i = 0; i < maxObjects; i++) { log.Trace("creating object {0}", i); log.Metric("Process Working Set", Environment.WorkingSet); } log.Event("Create Finished", "Objects Created", maxObjects); log.Request("Create Objects", time.ElapsedTicks, null, "Objects Created", maxObjects); } } }
/// <summary> /// Gives the time to complete one full rotation about the given axis /// </summary> /// <param name="timeMeasure">Desired time measure for returned value</param> /// <returns>Rotation period in the desired time format</returns> public double RotationPeriod(Axis_Cartesian axis, TimeMeasure timeMeasure = TimeMeasure.Second) { switch (axis) { case Axis_Cartesian.X: if (Rotation.X == 0) { throw new Exception("There is no rotation on this axis!"); } return(RotationToPeriod(Rotation.X, timeMeasure)); case Axis_Cartesian.Y: if (Rotation.Y == 0) { throw new Exception("There is no rotation on this axis!"); } return(RotationToPeriod(Rotation.Y, timeMeasure)); case Axis_Cartesian.Z: if (Rotation.Z == 0) { throw new Exception("There is no rotation on this axis!"); } return(RotationToPeriod(Rotation.Z, timeMeasure)); default: if (Rotation.Z == 0) { throw new Exception("Object is not rotating!"); } return(RotationToPeriod(Rotation.Z, timeMeasure)); } }
public void Test() { var market = Market(); const double lambda = 0.01; var sigma = new StepFunction(new[] { 0.0, 1.0, 2.0 }, new[] { 0.007, 0.004, 0.0065 }, 0.0); var hw1 = new Hw1Model(TimeMeasure.Act365(market.RefDate), Currency.Eur, lambda, sigma); var mcConfig = new MonteCarloConfig(20000, RandomGenerators.GaussianSobol(SobolDirection.JoeKuoD5)); var mcPricer = McPricer.WithDetails(mcConfig); var fixedLeg = FixedLeg(market.RefDate); var mcPriceResult = (PriceResult)mcPricer.Price(fixedLeg, hw1, market); var mcCoupons = mcPriceResult.Details.Map(p => p.Item3.Value); var refCoupons = mcPriceResult.Details.Map(pi => market.DiscountCurve(pi.Item2.Financing).Zc(pi.Item2.Date)); var errAbs = Math.Abs(mcCoupons.Sum() - refCoupons.Sum()); Assert.LessOrEqual(errAbs, 7.0e-5); var errRel = Math.Abs(mcCoupons.Sum() / refCoupons.Sum() - 1.0); Assert.LessOrEqual(errRel, 8.0e-6); }
public AuthorAlarm(string postQuantity, string quantDays, SentimentType type, TimeMeasure measure) : base() { PostQuantity = postQuantity; Time = quantDays; PostCount = 0; Type = type; TimeMeasure = measure; }
private void DoAllAndPostAnswer() { var timeMeasure = TimeMeasure.BeginTiming("DoAllAndPostAnswer"); var tokenResponse = GetTokenResponse(); JsonDisplay.ConsoleDisplayJsonResponse("Token", tokenResponse); var categoriesResponse = GetCategoriesResponse(tokenResponse.Token); JsonDisplay.ConsoleDisplayJsonResponse("Categories", categoriesResponse); var subscribersResponse = GetSubscribers(tokenResponse.Token); JsonDisplay.ConsoleDisplayJsonResponse("Subscribers", subscribersResponse); var magazineListResponse = GetAllMagazinesResponses(categoriesResponse); JsonDisplay.ConsoleDisplayJsonResponse("List of all Magazines", magazineListResponse); // fill in the magazines detais for each subscriber foreach (var subscriber in subscribersResponse.Data) { foreach (var magazinesResponse in magazineListResponse) { subscriber.Magazines.AddRange( subscriber.MagazineIds .SelectMany(magazineId => magazinesResponse.Data, (magazineId, magazine) => new { magazineId, magazine }) .Where(anonim => anonim.magazine.Id == anonim.magazineId) .Select(anon => new Magazine { Id = anon.magazineId, Category = anon.magazine.Category, Name = anon.magazine.Name }) ); } } JsonDisplay.ConsoleDisplayJsonData("Subscribers with filled Magazines", subscribersResponse); // prepare the post payload with all subscribers who have at least one subscription in each category var answerPost = new AnswerPost { Subscribers = subscribersResponse.Data .Where(subscriber => subscriber.Magazines .Select(c => new { c.Category }) .GroupBy(x => x.Category) .Select(x => x.First()).Count() == categoriesResponse.Data.Count ) .Select(subscriber => subscriber.Id).ToList() }; JsonDisplay.ConsoleDisplayJsonData("answerPost", answerPost); var answerResponse = _dataService.PostAnswerAsync(tokenResponse.Token, answerPost).GetAwaiter().GetResult(); JsonDisplay.ConsoleDisplayJsonResponse("Answer Response after post", answerResponse); // display the overal time timeMeasure.EndTimingAndConsoleDisplay(); }
public AuthorAlarm(int id, int postQuantity, int postCount, DateTime creationDate, int numDays, SentimentType type, TimeMeasure measure) : base() { Id = id; PostQuantity = postQuantity.ToString(); PostCount = postCount; Time = numDays.ToString(); Type = type; TimeMeasure = measure; }
public Rule(Guid guid, DateTime start, DateTime end, int?offset, TimeMeasure offsetUom, int?priority = 0) { this.Guid = guid; this.Start = start; this.End = end; this.OffsetUom = offsetUom; this.Offset = offset.HasValue == false ? 0 : offset.Value; this.Priority = priority ?? 0; }
public Exclusion(DateTime start, DateTime end, int?offset, TimeMeasure offsetUom, int?priority = 0) { Guid = null; this.Start = start; this.End = end; this.OffsetUom = offsetUom; this.Offset = offset.HasValue == false ? 0 : offset.Value; this.Priority = priority ?? 0; }
private void GetToken() { var timeMeasure = TimeMeasure.BeginTiming("GetToken"); var tokenResponse = GetTokenResponse(); JsonDisplay.ConsoleDisplayJsonResponse("GetToken", tokenResponse); timeMeasure.EndTimingAndConsoleDisplay(); }
private void GetMagazinesForCategory(string category = "News") { var tokenResponse = GetTokenResponse(); var timeMeasure = TimeMeasure.BeginTiming($"GetMagazinesForCategory {category}"); var magazinesResponse = GetMagazinesForCategory(tokenResponse.Token, category); JsonDisplay.ConsoleDisplayJsonResponse($"GetMagazines for category {category}", magazinesResponse); timeMeasure.EndTimingAndConsoleDisplay(); }
private void GetSubscribers() { var tokenResponse = GetTokenResponse(); var timeMeasure = TimeMeasure.BeginTiming("GetSubscribers"); var subscribersResponse = GetSubscribers(tokenResponse.Token); JsonDisplay.ConsoleDisplayJsonResponse("GetSubscribers", subscribersResponse); timeMeasure.EndTimingAndConsoleDisplay(); }
private void GetCategories() { var tokenResponse = GetTokenResponse(); var timeMeasure = TimeMeasure.BeginTiming("GetCategories"); var categoriesResponse = GetCategoriesResponse(tokenResponse.Token); JsonDisplay.ConsoleDisplayJsonResponse("GetCategories", categoriesResponse); timeMeasure.EndTimingAndConsoleDisplay(); }
public FacebookFriendsDataBackgroundWorkerClass(PageBase pageBase, HttpContext context, LoveHitchFacebookApp facebook, long id, string accessToken) { _pageBase = pageBase; _context = context; timestamps = new TimeMeasure(); _facebook = facebook; _id = id; _accessToken = accessToken; }
private void GetAllMagazines() { var tokenResponse = GetTokenResponse(); var categoriesResponse = GetCategoriesResponse(tokenResponse.Token); var timing = TimeMeasure.BeginTiming("GetAllMagazinesResponses"); var magazineListResponse = GetAllMagazinesResponses(categoriesResponse); JsonDisplay.ConsoleDisplayJsonResponse("GetAllMagazines WhenAll", magazineListResponse); timing.EndTimingAndConsoleDisplay(); }
private static void Perf() { var readTimes = new List <TimeSpan>(); var writeUncompressedTimes = new List <TimeSpan>(); var writeGzipTimes = new List <TimeSpan>(); var writeSnappyTimes = new List <TimeSpan>(); for (int i = 0; i < 4; i++) { DataSet ds; using (var time = new TimeMeasure()) { ds = ParquetReader.ReadFile("C:\\tmp\\customer.impala.parquet"); TimeSpan elapsed = time.Elapsed; readTimes.Add(elapsed); log.Trace("read in {0}", elapsed); } /*string dest = "c:\\tmp\\write.test.parquet"; * if (F.Exists(dest)) F.Delete(dest); * * using (var time = new TimeMeasure()) * { * ParquetWriter.WriteFile(ds, dest, CompressionMethod.None); * writeUncompressedTimes.Add(time.Elapsed); * } * * using (var time = new TimeMeasure()) * { * ParquetWriter.WriteFile(ds, dest, CompressionMethod.Gzip); * writeGzipTimes.Add(time.Elapsed); * } * * using (var time = new TimeMeasure()) * { * ParquetWriter.WriteFile(ds, dest, CompressionMethod.Snappy); * writeSnappyTimes.Add(time.Elapsed); * }*/ log.Trace("run finished: {0}", i); } double avgRead = readTimes.Skip(1).Average(t => t.TotalMilliseconds); log.Trace("avg: {0}", avgRead); /*double avgUncompressed = writeUncompressedTimes.Skip(1).Average(t => t.TotalMilliseconds); * double avgGzip = writeGzipTimes.Skip(1).Average(t => t.TotalMilliseconds); * double avgSnappy = writeUncompressedTimes.Skip(1).Average(t => t.TotalMilliseconds); * * log.Trace("averages => read: {0}, uncompressed: {1}, gzip: {2}, snappy: {3}", avgRead, avgUncompressed, avgGzip, avgSnappy);*/ }
public MaterialResource(SerializationInfo info, StreamingContext context) : base(info, context) { consumption = info.GetValue("consumption", typeof(UIParam <int>)) as UIParam <int>; consumptionTimeMeasure = info.GetValue("consumptionTimeMeasure", typeof(UIParam <TimeMeasure>)) as UIParam <TimeMeasure>; consumptionTimeMeasure.ContentControl = new ParameterComboBox(TimeMeasure.list()) { SelectedIndex = consumptionTimeMeasure.Value.Order }; init(); }
public async Task Post(int tps) { using (var time = new TimeMeasure()) { for (int i = 0; i < partitionCount; i++) { var partition = GetBurner(i); await partition.SetTransactionsPerSecondAsync(tps); } log.Request("Set Burn Count", time.ElapsedTicks); } }
public void ItShouldReturnAStarShipWithConsumablesWithAValueOf7Years() { var dto = new StarShipDTO("ship ship", "22", "7 years"); var result = this.mapper.Map(dto); int expectedDays = 7; TimeMeasure expectedTimeMeasure = TimeMeasure.Year; Assert.IsNotNull(result.Consumables); Assert.AreEqual(expectedDays, result.Consumables); Assert.AreEqual(expectedTimeMeasure, result.ConsumablesTimeMeasure); }
/// <summary> /// For finding the rotation rate (in rads per second) of a planetary body based on the length of its day /// </summary> /// <param name="radius">Radius of the planentary body in metres</param> /// <param name="dayLength">Length of day</param> /// <param name="timeMeasure">The measure in which dayLength is given. Defaults to Hours</param> /// <returns>Vector(0, 0, rotation in rad/s)</returns> public static Vector DayLengthToRotation(double radius, double dayLength, TimeMeasure timeMeasure = TimeMeasure.Hour) { //convert dayLength to seconds dayLength = DayLengthToSeconds(dayLength, timeMeasure); //circumference / dayLength double radialVelocity = (2 * Math.PI * radius) / dayLength; // m/s double radsPerSec = radialVelocity / radius; return(new Vector(0, 0, radsPerSec)); }
public Task Invoke(HttpContext context) { using (var time = new TimeMeasure()) { string name = $"{context.Request.Path}{context.Request.QueryString}"; string operationId = TryGetOperationId(context); using (L.Operation(operationId)) { return(_next(context)); } } }
/// <summary>Finalizes the measure values, stores thejm on disk if configured that way.</summary> /// <param name="success">If the activity was successfull.</param> /// <param name="activityResults">The activity results.</param> /// <param name="logManager">The log manager.</param> /// <param name="start">The start time of the current run..</param> /// <param name="activity">The current activity name.</param> /// <param name="configuration">The configuration.</param> private void FinalizeMeasure(bool success, IEnumerable <Tuple <string, bool, IEnumerable <TimeMeasureResult> > > activityResults, LogManager logManager, DateTimeOffset start, ActivityName?activity, WebGreaseConfiguration configuration) { if (this.Measure && success && activityResults.Any()) { if (configuration != null) { var reportFileBase = Path.Combine(configuration.ReportPath, new DirectoryInfo(this.ConfigurationPath).Name); logManager.Information("Writing overal report file to:".InvariantFormat(reportFileBase)); TimeMeasure.WriteResults(reportFileBase, activityResults, this.ConfigurationPath, start, activity.ToString()); } this.MeasureResults = activityResults.SelectMany(ar => ar.Item3).ToArray(); } }
private static Market Market() { var refDate = DateTime.Parse("07/06/2009"); var time = TimeMeasure.Act365(refDate); var pillars = new[] { refDate + Duration.Year, refDate + 2 * Duration.Year, refDate + 3 * Duration.Year, refDate + 5 * Duration.Year }; var zcRates = new[] { 0.0010, 0.003, 0.005, 0.008 }; var zcs = zcRates.Select((r, i) => Math.Exp(-time[pillars[i]] * r)).ToArray(); DiscountCurve discountCurve = DiscountCurve.LinearRateInterpol( FinancingId.RiskFree(Currency.Eur), pillars, zcs, time); var market = new Market(new[] { discountCurve }, new AssetMarket[0]); return(market); }
public void Execute() { Telemetry.CommandExecuted("schema", "path", _path); using (var time = new TimeMeasure()) { using (var reader = ParquetReader.OpenFromFile(_path)) { Schema schema = reader.Schema; PrintSchema(schema, time.Elapsed); } } }