当前位置: 首页>>代码示例>>C#>>正文


C# Stopwatch类代码示例

本文整理汇总了C#中Stopwatch的典型用法代码示例。如果您正苦于以下问题:C# Stopwatch类的具体用法?C# Stopwatch怎么用?C# Stopwatch使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Stopwatch类属于命名空间,在下文中一共展示了Stopwatch类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: OnBeginRequest

        private static void OnBeginRequest(object sender, EventArgs e) {
            var context = (HttpApplication)sender;

            // TaskCreationOptions.PreferFairness 를 지정해야, StartNew() 메소드를 바로 시작한다.
            var stopwatchTask
                = new Task<Lazy<double>>(() => {
                                             var sw = new Stopwatch();
                                             sw.Start();

                                             if(IsDebugEnabled) {
                                                 var request = context.Request;
                                                 log.Debug(BeginRequestLogFormat,
                                                           request.UserHostAddress,
                                                           request.RequestType,
                                                           request.CurrentExecutionFilePath);
                                             }

                                             // Lazy 값을 처음 호출할 때, stop watch가 끝나고, 경과 값을 반환한다.
                                             return new Lazy<double>(() => {
                                                                         sw.Stop();
                                                                         return sw.ElapsedMilliseconds;
                                                                     });
                                         });
            stopwatchTask.Start();

            Local.Data[AsyncAccessLogModuleKey] = stopwatchTask;
        }
开发者ID:debop,项目名称:NFramework,代码行数:27,代码来源:AsyncAccessLogModule.cs

示例2: Export

        /// <summary>
        /// Экспортирует массив данных в XLSX формат с учетом выбранной локали
        /// </summary>
        /// <param name="path">Путь к файлу, в который нужно сохранить данные</param>
        /// <param name="localisation">Локализация</param>
        /// <returns>Успешное завершение операции</returns>
        public override bool Export(String path, Localisation localisation)
        {
            try
            {
                if (!path.EndsWith(".xlsx"))
                    path += ".xlsx";

                log.Info(String.Format("Export to .xlsx file to: {0}", path));
                var timer = new Stopwatch();
                timer.Start();
                var file = new FileInfo(path);
                using (var pck = new ExcelPackage(file))
                {
                    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
                    ws.Cells["A1"].LoadFromDataTable(dataTable, true);
                    ws.Cells.AutoFitColumns();
                    pck.Save();
                }

                timer.Stop();
                log.Info(String.Format("Export complete! Elapsed time: {0} ms", timer.Elapsed.Milliseconds));
                return true;
            }
            catch (Exception ex)
            {
                log.Error("Can't export to .xlsx file!", ex);
                return false;
            }
        }
开发者ID:nozdrenkov,项目名称:CSVConverter,代码行数:35,代码来源:XLSXConverter.cs

示例3: Main

        public static void Main()
        {
            #if DEBUG
            Console.SetIn(new System.IO.StreamReader(@"../../test.020.in.txt"));
            Debug.Listeners.Add(new ConsoleTraceListener());
            #endif

            Stopwatch sw = new Stopwatch();
            sw.Start();
            StringBuilder sb = new StringBuilder();
            int lines = int.Parse(Console.ReadLine());
            for (int i = 0; i < lines; i++)
            {
                string line = Console.ReadLine();

                bool isValid = Validate(line);
                if (isValid)
                {
                    sb.AppendLine("VALID");
                }
                else
                {
                    sb.AppendLine("INVALID");
                }
            }
            sw.Stop();
            Console.Write(sb.ToString());
            Debug.WriteLine(sw.Elapsed);
            string bla = "asdlj";
        }
开发者ID:vanndann,项目名称:TelerikAcademy,代码行数:30,代码来源:Program.cs

示例4: RectangleTransparent

        public RectangleTransparent()
        {
            clearPen = new Pen(Color.FromArgb(1, 0, 0, 0));
            borderDotPen = new Pen(Color.Black, 1);
            borderDotPen2 = new Pen(Color.White, 1);
            borderDotPen2.DashPattern = new float[] { 5, 5 };
            penTimer = Stopwatch.StartNew();
            ScreenRectangle = CaptureHelpers.GetScreenBounds();

            surface = new Bitmap(ScreenRectangle.Width, ScreenRectangle.Height);
            gSurface = Graphics.FromImage(surface);
            gSurface.InterpolationMode = InterpolationMode.NearestNeighbor;
            gSurface.SmoothingMode = SmoothingMode.HighSpeed;
            gSurface.CompositingMode = CompositingMode.SourceCopy;
            gSurface.CompositingQuality = CompositingQuality.HighSpeed;
            gSurface.Clear(Color.FromArgb(1, 0, 0, 0));

            StartPosition = FormStartPosition.Manual;
            Bounds = ScreenRectangle;
            Text = "ShareX - " + Resources.RectangleTransparent_RectangleTransparent_Rectangle_capture_transparent;

            Shown += RectangleLight_Shown;
            KeyUp += RectangleLight_KeyUp;
            MouseDown += RectangleLight_MouseDown;
            MouseUp += RectangleLight_MouseUp;

            using (MemoryStream cursorStream = new MemoryStream(Resources.Crosshair))
            {
                Cursor = new Cursor(cursorStream);
            }

            timer = new Timer { Interval = 10 };
            timer.Tick += timer_Tick;
            timer.Start();
        }
开发者ID:KamilKZ,项目名称:ShareX,代码行数:35,代码来源:RectangleTransparent.cs

示例5: Main

        static void Main(string[] args)
        {
            ///===========================================
            ///Unzip the archive in the project directory
            ///===========================================

            Stopwatch sw = new Stopwatch();
            TrieNode start = new TrieNode();
            Dictionary<string, int> wordsInDictionary = new Dictionary<string, int>();
            var words = SetInputText();


            PopulateDictionary(sw, words, wordsInDictionary);

            //takes about 9 secs
            PopulateTrie(sw, start, words);

            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Word: {0}", words[i].ToString());


                SearchInTrie(sw, start, words, words[i].ToString());

                SearchInDictionary(sw, wordsInDictionary, words, words[i].ToString());
            }
        }
开发者ID:Dyno1990,项目名称:TelerikAcademy-1,代码行数:27,代码来源:wordOccuranceOld.cs

示例6: TestArgumentNullCheckSpeed

        private static void TestArgumentNullCheckSpeed(int numberOfCalls)
        {
            var test1 = new Test1();
            var test2 = new Test2();
            var normalNullParameterCheckingTesting = new NormalNullParameterCheckingTesting();
            var stopWatch = new Stopwatch();

            stopWatch.Start();

            for (var i = 0; i < numberOfCalls; i++)
            {
                normalNullParameterCheckingTesting.TestWith1(test1);
            }

            Console.WriteLine("Normal null checking speed with 1 Test parameter: " + stopWatch.ElapsedMilliseconds);

            stopWatch.Restart();

            for (var i = 0; i < numberOfCalls; i++)
            {
                normalNullParameterCheckingTesting.TestWith2(test1, test2);
            }

            Console.WriteLine("Normal null checking speed with 2 Test parameter: " + stopWatch.ElapsedMilliseconds);
        }
开发者ID:RichardWilliams,项目名称:ParameterValidator,代码行数:25,代码来源:Program.cs

示例7: DoStuff

        public static void DoStuff(ProgramOptions options)
        {
            Options = options;
            GlobalStopwatch = Stopwatch.StartNew();

            DumpSettings(Options);

            if (!Options.ShowTitles && Options.ShouldLog)
            {
                foreach (var output in Outputs)
                {
                    ConsoleExtensions.WriteLineColor(output.OutputColor, output.Name);
                }
            }

            Iterations = Options.NumberOfIterations;
            for (var i = 1; i <= Iterations; i++)
            {
                ConsoleExtensions.WriteLine($"Iteration {i}".ToUpper());

                foreach (var increment in Increments)
                {
                    RunIncrement(increment);
                }
            }
            GlobalStopwatch.Stop();
            if (Options.ShouldOutput) WriteOutputs(DateTime.UtcNow);
            if (Options.ShouldHaltOnEnd) ConsoleExtensions.WriteLine("DONE");
            if (Options.ShouldHaltOnEnd) Console.ReadLine();
        }
开发者ID:StubbleOrg,项目名称:Stubble,代码行数:30,代码来源:Program.cs

示例8: DashboardView

        public DashboardView()
        {
            InitializeComponent();

            AndonManager = new AndonManager(StationList, null, Andonmanager.AndonManager.MODE.MASTER);

            AndonManager.start();
            StationList = new Queue<int>();

            Plans = new Plans();
            PlanGrid.DataContext = Plans;

            Actuals = new Models.Actuals();
            ActualGrid.DataContext = Actuals;

            AppTimer = new Timer(1000);
            AppTimer.AutoReset = false;
            AppTimer.Elapsed += AppTimer_Elapsed;

            EfficiencyWatch = new Stopwatch();

            using (PSBContext DBContext = new PSBContext())
            {

                Shifts = DBContext.Shifts.ToList();

                foreach (Shift s in Shifts)
                {
                    s.Update();
                }

            }

            AppTimer.Start();
        }
开发者ID:JugaadSolutions,项目名称:ProductionScoreBoard,代码行数:35,代码来源:DashboardView.xaml.cs

示例9: when_sending_message_with_session_then_session_receiver_gets_both_messages_fast

        public void when_sending_message_with_session_then_session_receiver_gets_both_messages_fast()
        {
            var sender = this.Settings.CreateTopicClient(this.Topic);
            var signal = new AutoResetEvent(false);
            var body1 = Guid.NewGuid().ToString();
            var body2 = Guid.NewGuid().ToString();
            var stopWatch = new Stopwatch();

            var receiver = new SessionSubscriptionReceiver(this.Settings, this.Topic, this.Subscription);

            sender.Send(new BrokeredMessage(body1) { SessionId = "foo" });
            sender.Send(new BrokeredMessage(body2) { SessionId = "bar" });

            var received = new ConcurrentBag<string>();

            receiver.Start(
                m =>
                {
                    received.Add(m.GetBody<string>());
                    signal.Set();
                    return MessageReleaseAction.CompleteMessage;
                });

            signal.WaitOne();
            stopWatch.Start();
            signal.WaitOne();
            stopWatch.Stop();

            receiver.Stop();

            Assert.Contains(body1, received);
            Assert.Contains(body2, received);
            Assert.InRange(stopWatch.Elapsed, TimeSpan.Zero, TimeSpan.FromSeconds(2));
        }
开发者ID:TiagoTerra,项目名称:cqrs-journey,代码行数:34,代码来源:SessionSubscriptionReceiverIntegration.cs

示例10: PerformanceListByTeam_With10000BunniesRandomlyDistributedIn5000RoomsInSameTeam

        public void PerformanceListByTeam_With10000BunniesRandomlyDistributedIn5000RoomsInSameTeam()
        {
            //Arrange
            var roomsCount = 5000;
            var bunniesCount = 10000;
            for (int i = 0; i < roomsCount; i++)
            {
                this.BunnyWarCollection.AddRoom(i);
            }
            for (int i = 0; i < bunniesCount; i++)
            {
                this.BunnyWarCollection.AddBunny(i.ToString(), 2, this.Random.Next(0, roomsCount));
            }

            //Act
            Stopwatch timer = new Stopwatch();
            timer.Start();
            for (int i = 0; i < 10000; i++)
            {
                var result = this.BunnyWarCollection.ListBunniesByTeam(2).Count();
                Assert.AreEqual(10000, result, "Incorrect count of bunnies returned by List By Team Command!");
            }
            timer.Stop();
            Assert.IsTrue(timer.ElapsedMilliseconds < 100);
        }
开发者ID:simooo93,项目名称:Exams,代码行数:25,代码来源:ListBunniesByTeamPerformance.cs

示例11: Build

 public void Build()
 {
     _stateHash.Clear();
       Stopwatch sw = new Stopwatch();
       sw.Start();
       var i1 = sw.ElapsedMilliseconds;
       Data = _language.ParserData;
       CheckPrecedenceSettings(_language.GrammarData, Data.ParseMethod);
       var i2 = sw.ElapsedMilliseconds;
       var i3 = sw.ElapsedMilliseconds;
       CreateLalrParserStates();
       var i4 = sw.ElapsedMilliseconds;
       //TODO: move all the following to a single method
       //ComputeTransitionIncludesAndItemLookbacks();  //5 ms
       var i5 = sw.ElapsedMilliseconds;
       PropagateTransitionsIncludes(0);               //220 ms
       var i6 = sw.ElapsedMilliseconds;
       //ComputeTransitionsSources(0);
       var i7 = sw.ElapsedMilliseconds;
       ComputeLookaheads();
       var i8 = sw.ElapsedMilliseconds;
       var i9 = sw.ElapsedMilliseconds;
       ComputeAndResolveConflicts();
       var i10 = sw.ElapsedMilliseconds;
       var i11 = sw.ElapsedMilliseconds;
       var i12 = sw.ElapsedMilliseconds;
       if (Data.ParseMethod == ParseMethod.Nlalr) {
     SwitchConflictingStatesToNonCanonicalLookaheads();
       }
       var i13 = sw.ElapsedMilliseconds;
       ReportAndSetDefaultActionsForConflicts();
       CreateReduceActions();
       ComputeStateExpectedLists();
 }
开发者ID:TheByte,项目名称:sones,代码行数:34,代码来源:ParserDataBuilder.cs

示例12: Main

        static void Main(string[] args)
        {
            var sw = new Stopwatch();
            sw.Start();
            try
            {
                var options = new Options();

                if (CommandLine.Parser.Default.ParseArguments(args, options))
                {
                    var processor = new Processor();

                    if (options.SiteAnalysisMode)
                    {
                        processor.AnalyzeWebSites(options).Wait();
                    }
                    else
                    {
                        processor.AnalyzeWebPages(options).Wait();
                    }
                }
            }
            catch (AggregateException ex)
            {
                foreach (var exception in ex.InnerExceptions)
                {
                    Console.Error.WriteLine(exception.Message);
                }
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
        }
开发者ID:sbezludny,项目名称:CssOptimizer,代码行数:32,代码来源:Program.cs

示例13: BXSSMainWindow

    public BXSSMainWindow()
    {
        _settings = new BXSSSettings();
        _settings.Load();
        _screenshot = new Screenshot(
            KSPUtil.ApplicationRootPath + "PluginData/BXSS/",
            () =>
                {
                    _prevUIState = Visible;
                    Visible = false;
                    if(_mainUIEnabled)
                        RenderingManager.ShowUI(false);
                },
            () =>
                {
                    Visible = _prevUIState;
                    if(_mainUIEnabled)
                        RenderingManager.ShowUI(true);
                });

        _collapsed = true;
        _mainUIEnabled = true;
        _autoIntervalEnabled = false;

        _autoIntervalStopwatch = new Stopwatch();

        WindowPosition = _settings.WindowPosition;

        Caption = "B.X.S.S";

        SetupControls();
    }
开发者ID:kaylynb,项目名称:BXSS,代码行数:32,代码来源:BXSSMainWindow.cs

示例14: ComputeTimesPrimes

 public void ComputeTimesPrimes()
 {
     Stopwatch w = new Stopwatch();
     w.Start();
     PrimeNumbers.GeneratePrimeNumbers1(100000);
     Console.WriteLine("Primes 1: " + w.ElapsedMilliseconds.ToString());
     w.Stop();
     w.Reset();
     w.Start();
     PrimeNumbers.GeneratePrimeNumbers2(100000);
     Console.WriteLine("Primes 2: "+ w.ElapsedMilliseconds.ToString());
     w.Stop();
     w.Reset();
     w.Start();
     PrimeNumbers.GeneratePrimeNumbers3(100000);
     Console.WriteLine("Primes 3: " + w.ElapsedMilliseconds.ToString());
     w.Stop();
     w.Start();
     for (int i = 1; i <= 100000; i++)
     {
         int mod = i % 2;
     }
     w.Stop();
     Console.WriteLine("Primes 4: " + w.ElapsedMilliseconds.ToString());
 }
开发者ID:rajeevag,项目名称:Algorithms,代码行数:25,代码来源:PrimeNumberTests.cs

示例15: CastSpellAction

        public CastSpellAction()
        {
            _spamControl = new Stopwatch();
            QueueIsRunning = false;
            Properties["Casted"] = new MetaProp("Casted", typeof(int), new ReadOnlyAttribute(true));
            Properties["SpellName"] = new MetaProp("SpellName", typeof(string), new ReadOnlyAttribute(true));
            Properties["Repeat"] = new MetaProp("Repeat", typeof(DynamicProperty<int>),
                new TypeConverterAttribute(typeof(DynamicProperty<int>.DynamivExpressionConverter)));
            Properties["Entry"] = new MetaProp("Entry", typeof(uint));
            Properties["CastOnItem"] = new MetaProp("CastOnItem", typeof(bool), new DisplayNameAttribute("Cast on Item"));
            Properties["ItemType"] = new MetaProp("ItemType", typeof(InventoryType), new DisplayNameAttribute("Item Type"));
            Properties["ItemId"] = new MetaProp("ItemId", typeof(uint));
            Properties["RepeatType"] = new MetaProp("RepeatType", typeof(RepeatCalculationType), new DisplayNameAttribute("Repeat Type"));
            // Properties["Recipe"] = new MetaProp("Recipe", typeof(Recipe), new TypeConverterAttribute(typeof(RecipeConverter)));

            Casted = 0;
            Repeat = new DynamicProperty<int>(this,"1");
            RegisterDynamicProperty("Repeat");
            Entry = 0u;
            RepeatType = RepeatCalculationType.Craftable;
            Recipe = null;
            CastOnItem = false;
            ItemType = InventoryType.Chest;
            ItemId = 0u;
            Properties["SpellName"].Value = SpellName;

            //Properties["Recipe"].Show = false;
            Properties["ItemType"].Show = false;
            Properties["ItemId"].Show = false;
            Properties["Casted"].PropertyChanged += OnCounterChanged;
            CheckTradeskillList();
            Properties["RepeatType"].PropertyChanged += CastSpellActionPropertyChanged;
            Properties["Entry"].PropertyChanged += OnEntryChanged;
            Properties["CastOnItem"].PropertyChanged += CastOnItemChanged;
        }
开发者ID:swypemaster,项目名称:saintsorsinners,代码行数:35,代码来源:CastSpellAction.cs


注:本文中的Stopwatch类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。