Example #1
0
        public void Constructor_Test()
        {
            TimeMeasurer _timeMeasurer = new TimeMeasurer();

            Assert.IsNotNull(_timeMeasurer);
            Assert.IsNull(_timeMeasurer.AverageTime);
        }
 public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
     RequestStatus.ControllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
     RequestStatus.ActionName     = filterContext.ActionDescriptor.ActionName;
     RequestStatus.Parameters     = filterContext.ActionDescriptor.GetParameters()
                                    .Select(x => string.Concat((string)x.ParameterType.Name, (string)" ", (string)x.ParameterName)).ToArray();
     _totalRequestTimeMeasurer = new TimeMeasurer().Start();
     _totalActionTimeMeasurer  = new TimeMeasurer().Start();
 }
Example #3
0
    public static async Task AsyncMain()
    {
        int a       = 500;
        int b       = 10;
        var results = await TimeMeasurer.Start(() => Function(a, b));

        Console.WriteLine("Waited: {0}", results.Duration.TotalSeconds);
        Console.WriteLine("Result: {0}", results.Result);
    }
Example #4
0
        public void Measurer_Test()
        {
            TimeMeasurer _timeMeasurer = new TimeMeasurer();

            _timeMeasurer.Start();
            _timeMeasurer.Stop();
            if (_timeMeasurer.AverageTime != null && _timeMeasurer.AverageTime.HasValue)
            {
                Assert.LessOrEqual(0, _timeMeasurer.AverageTime.Value);
            }
            _timeMeasurer.Reset();
            Assert.IsNull(_timeMeasurer.AverageTime);
        }
        public void ShouldReturnNanosecondsForExactlyOneSecond()
        {
            // Arrange
            var nanosecondsPerSecond = 1000000000;
            var start        = 1234567890L;
            var stop         = start + nanosecondsPerSecond;
            var timeMeasurer = new TimeMeasurer(start, stop, nanosecondsPerSecond);

            // Act
            var result = timeMeasurer.Nanoseconds;

            // Assert
            Assert.That(result, Is.EqualTo(nanosecondsPerSecond));
        }
        public void ShouldReturnTimeSpanForExactlyOneSecond()
        {
            // Arrange
            var millisecondsPerSecond = 1000;
            var nanosecondsPerSecond  = 1000000000;
            var start        = 1234567890L;
            var stop         = start + nanosecondsPerSecond;
            var timeMeasurer = new TimeMeasurer(start, stop, nanosecondsPerSecond);

            // Act
            var result = timeMeasurer.TimeSpan;

            // Assert
            Assert.That(result.TotalMilliseconds, Is.EqualTo(millisecondsPerSecond));
        }
        /// <summary>
        /// Should be used to keep track of current subscriptions
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            log.Info($"Queued Audio Status Service is starting");

            while (!stoppingToken.IsCancellationRequested)
            {
                // Audio status
                while (HasSubscriptions && !stoppingToken.IsCancellationRequested)
                {
                    int waitTime;
                    using (var timeMeasurer = new TimeMeasurer("AudioStatusService checking on all codecs"))
                    {
                        //var sipAddresses = Subscriptions.Select(s => s.SipAddress).Distinct().ToList();
                        var subs = Subscriptions.Distinct().ToList();
                        log.Debug($"AudioStatusService Checking audio status on #{subs.Count} codec(s).");

                        Parallel.ForEach(subs, async sub =>
                        {
                            using (new TimeMeasurer($"AudioStatusService Checking for {sub.SipAddress}"))
                            {
                                //if (sub.CodecApiHasWebsocket)
                                //{
                                //    await StartWebsocketConnectionToCodec(sub.SipAddress);
                                //}
                                //else
                                //{
                                await CheckAudioStatusOnCodecAsync(sub.SipAddress);
                                //}
                            }
                        });

                        waitTime = (int)Math.Max(_pollDelay.Subtract(timeMeasurer.ElapsedTime).TotalMilliseconds, 0);
                    }
                    log.Trace($"AudioStatusService Waiting {waitTime} ms until next update");
                    await Task.Delay(waitTime);
                }

                if (!stoppingToken.IsCancellationRequested)
                {
                    log.Trace("AudioStatusService / Linestatus has no subscriptions");
                    await Task.Delay(1000); // Wait until next check for HasSubscriptions
                }
            }

            log.Info("AudioStatusService finished");
        }
Example #8
0
        public static void Initialize(FileInfo file)
        {
            TimeMeasurer.MeasureTime("new DataFactory();", () =>
            {
                if (DataFactory == null)
                {
                    DataFactory = new DataFactory(file, false);
                }
            });
            TimeMeasurer.MeasureTime("DataFactory.Create();", () =>
            {
                DataFactory?.Create();
            });

            if (SessionFactory == null)
            {
                SessionFactory = DataFactory.CreateSessionFactory();
            }
        }
Example #9
0
        public static void ChangeFiles(InputData input)
        {
            var files   = Dir.GetFiles(input);
            var changer = ChangingFile.GetChange(input.Modifier);

            Action act = new FileChanger(changer);

            act = new TimeMeasurer(act);
            act = new CheckPermission(act);

            foreach (var file in files)
            {
                changer.FileForChange = file;

                act.Act();

                file.Save();
            }
        }
Example #10
0
 public Mp3Renamer(TimeMeasurer timeMeasurer)
 {
     _timeMeasurer = timeMeasurer;
 }
Example #11
0
        internal async Task <ContentFactory> LoadAsync(LottieVisualOptions options)
        {
            LottieVisualDiagnostics diagnostics = null;
            var timeMeasurer = TimeMeasurer.Create();

            if (options.HasFlag(LottieVisualOptions.IncludeDiagnostics))
            {
                diagnostics = new LottieVisualDiagnostics {
                    Options = options
                };
            }

            var result = new ContentFactory(diagnostics);

            // Get the file name and JSON contents.
            (var fileName, var jsonStream) = await GetJsonStreamAsync();

            if (diagnostics != null)
            {
                diagnostics.FileName = fileName;
                diagnostics.ReadTime = timeMeasurer.GetElapsedAndRestart();
            }

            if (jsonStream is null)
            {
                // Failed to load ...
                return(result);
            }

            // Parsing large Lottie files can take significant time. Do it on
            // another thread.
            LottieComposition lottieComposition = null;

            await CheckedAwaitAsync(Task.Run(() =>
            {
                lottieComposition =
                    LottieCompositionReader.ReadLottieCompositionFromJsonStream(
                        jsonStream,
                        LottieCompositionReader.Options.IgnoreMatchNames,
                        out var readerIssues);

                if (diagnostics != null)
                {
                    diagnostics.JsonParsingIssues = ToIssues(readerIssues);
                }
            }));

            if (diagnostics != null)
            {
                diagnostics.ParseTime = timeMeasurer.GetElapsedAndRestart();
            }

            if (lottieComposition is null)
            {
                // Failed to load...
                return(result);
            }

            if (diagnostics != null)
            {
                // Save the LottieComposition in the diagnostics so that the xml and codegen
                // code can be derived from it.
                diagnostics.LottieComposition = lottieComposition;

                // Validate the composition and report if issues are found.
                diagnostics.LottieValidationIssues = ToIssues(LottieCompositionValidator.Validate(lottieComposition));
                diagnostics.ValidationTime         = timeMeasurer.GetElapsedAndRestart();
            }

            result.SetDimensions(
                width: lottieComposition.Width,
                height: lottieComposition.Height,
                duration: lottieComposition.Duration);

            // Translating large Lotties can take significant time. Do it on another thread.
            WinCompData.Visual wincompDataRootVisual = null;
            uint requiredUapVersion  = 0;
            var  optimizationEnabled = options.HasFlag(LottieVisualOptions.Optimize);

            TranslationResult translationResult;

            await CheckedAwaitAsync(Task.Run(() =>
            {
                // Generate property bindings only if the diagnostics object was requested.
                // This is because the binding information is output in the diagnostics object
                // so there's no point translating bindings if the diagnostics object
                // isn't available.
                var makeColorsBindable = diagnostics != null && options.HasFlag(LottieVisualOptions.BindableColors);
                translationResult      = LottieToWinCompTranslator.TryTranslateLottieComposition(
                    lottieComposition: lottieComposition,
                    configuration: new TranslatorConfiguration
                {
                    TranslatePropertyBindings = makeColorsBindable,
                    GenerateColorBindings     = makeColorsBindable,
                    TargetUapVersion          = GetCurrentUapVersion(),
                });

                wincompDataRootVisual = translationResult.RootVisual;
                requiredUapVersion    = translationResult.MinimumRequiredUapVersion;

                if (diagnostics != null)
                {
                    diagnostics.TranslationIssues = ToIssues(translationResult.TranslationIssues);
                    diagnostics.TranslationTime   = timeMeasurer.GetElapsedAndRestart();

                    // If there were any property bindings, save them in the Diagnostics object.
                    if (translationResult.SourceMetadata.TryGetValue(s_propertyBindingNamesKey, out var propertyBindingNames))
                    {
                        diagnostics.ThemePropertyBindings = (IReadOnlyList <PropertyBinding>)propertyBindingNames;
                    }
                }

                // Optimize the resulting translation. This will usually significantly reduce the size of
                // the Composition code, however it might slow down loading too much on complex Lotties.
                if (wincompDataRootVisual != null && optimizationEnabled)
                {
                    // Optimize.
                    wincompDataRootVisual = UIData.Tools.Optimizer.Optimize(wincompDataRootVisual, ignoreCommentProperties: true);

                    if (diagnostics != null)
                    {
                        diagnostics.OptimizationTime = timeMeasurer.GetElapsedAndRestart();
                    }
                }
            }));

            if (wincompDataRootVisual is null)
            {
                // Failed.
                return(result);
            }
            else
            {
                if (diagnostics != null)
                {
                    // Save the root visual so diagnostics can generate XML and codegen.
                    diagnostics.RootVisual         = wincompDataRootVisual;
                    diagnostics.RequiredUapVersion = requiredUapVersion;
                }

                result.SetRootVisual(wincompDataRootVisual);
                return(result);
            }
        }
 public override void OnResultExecuting(ResultExecutingContext filterContext)
 {
     _totalResultTimeMeasurer = new TimeMeasurer().Start();
 }
Example #13
0
        /**
         * Overloaded method. Note that the last parameter can be null if we only want to compare
         * results from different implementations.
         * The second last parameter is used when we also have an expected path retrieved for example from an xml file.
         * The last parameter can be used temporarirly for "debugging" purposes when we want to display the results to the console
         * See comment at class level.
         */
        public void AssertExpectedResultsOrAssertImplementationsWithEachOther(
            IList <Edge> edgesForBigGraph,
            Vertex startVertex,
            Vertex endVertex,
            int numberOfPathsToFind,
            IList <PathFinderFactory> pathFinderFactoriesForImplementationsToTest,
            IList <Path> expectedListOfPaths,
            string optionalPathToResourceXmlFile,
            bool shouldTestResultsWithImplementationsAgainstEachOther = false
            )
        {
            // TODO: clean up this method e.g. regarding "shouldAlsoTestResultsWithImplementationsAgainstEachOther"
            //this.SetConsoleOutputDesired(ConsoleOutputDesired.TIME_MEASURE);
            string messagePrefixWithInformationAboutXmlSourcefileWithTestData = optionalPathToResourceXmlFile == null ? "" : "Xml file with test data: " + optionalPathToResourceXmlFile + " . ";

            output("Number of edges in the graph to be tested : " + edgesForBigGraph.Count);
            IDictionary <string, IList <Path> > shortestPathsPerImplementation = new Dictionary <string, IList <Path> >();

            // the parameter GraphEdgesValidationDesired.NO will be used so therefore do the validation once externally here first
            GraphEdgesValidator <Path, Edge, Vertex, Weight> .ValidateEdgesForGraphCreation <Path, Edge, Vertex, Weight>(edgesForBigGraph);

            PathParser <Path, Edge, Vertex, Weight> pathParser = PathParser <Path, Edge, Vertex, Weight> .CreatePathParserDefault(edgesForBigGraph);

            //assertThat("At least some implementation should be used", pathFinderFactoriesForImplementationsToTest.size(), greaterThanOrEqualTo(1));
            // TODO: "hamcrest" syntax similar to above java code
            Assert.That(pathFinderFactoriesForImplementationsToTest.Count >= 1, "At least some implementation should be used");
            for (int i = 0; i < pathFinderFactoriesForImplementationsToTest.Count; i++)
            {
                PathFinderFactory pathFinderFactory = pathFinderFactoriesForImplementationsToTest[i];
                output("Will now test file " + optionalPathToResourceXmlFile + " with impl " + pathFinderFactory.GetType().Name);
                TimeMeasurer tm         = TimeMeasurer.Start();
                PathFinder   pathFinder = pathFinderFactory.CreatePathFinder(
                    edgesForBigGraph,
                    GraphEdgesValidationDesired.NO                 // do the validation one time instead of doing it for each pathFinderFactory
                    );
                IList <Path> shortestPaths = pathFinder.FindShortestPaths(startVertex, endVertex, numberOfPathsToFind);
                Assert.IsNotNull(shortestPaths);
                //assertThat("At least some path should be found", shortestPaths.size(), greaterThanOrEqualTo(1));
                Assert.That(shortestPaths.Count >= 1, "At least some path should be found"); // TODO "hamcrest" syntax as java above
                output(
                    messagePrefixWithInformationAboutXmlSourcefileWithTestData
                    + "Seconds: " + tm.GetSeconds()
                    + ". Implementation: " + pathFinder.GetType().Name,
                    ConsoleOutputDesired.TIME_MEASURE
                    );
                if (isAllConsoleOutputDesired())
                {
                    DisplayListOfShortestPath(shortestPaths);
                    output("Implementation class for above and below output: " + pathFinderFactory.GetType().Name);
                    DisplayAsPathStringsWhichCanBeUsedInXml(shortestPaths, pathParser);
                }
                shortestPathsPerImplementation.Add(pathFinder.GetType().Name, shortestPaths);
            }
            IList <string> nameOfImplementations = new List <string>(shortestPathsPerImplementation.Keys);

            if (expectedListOfPaths != null)
            {
                AssertResultsWithExpectedPaths(
                    expectedListOfPaths,
                    optionalPathToResourceXmlFile,
                    shortestPathsPerImplementation
                    );
            }
            else // if(expectedListOfPaths != null) {
            if (shouldTestResultsWithImplementationsAgainstEachOther)
            {
                AssertResultsWithImplementationsAgainstEachOther(
                    optionalPathToResourceXmlFile,
                    shortestPathsPerImplementation
                    );
            }
        }
Example #14
0
 internal OutQueueManager(string source)
 {
     capacityInfoTimeMeasurer = new TimeMeasurer(source, new TimeSpan(0, 1, 0, 0));
 }
Example #15
0
 internal OutQueueManager()
 {
     capacityInfoTimeMeasurer = new TimeMeasurer("QueueManager", new TimeSpan(0, 1, 0, 0));
 }