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


C# Diagnostics.Stopwatch类代码示例

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


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

示例1: button1_Click

        private void button1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            var ControllerIPAddress = new IPAddress(new byte[] { 192, 168, 0, 2 });
            var ControllerPort = 40001;
            var ControllerEndPoint = new IPEndPoint(ControllerIPAddress, ControllerPort);
            _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            var header = "@";
            var command = "00C";
            var checksum = "E3";
            var end = "\r\n";
            var data = header + command + checksum + end;
            byte[] bytes = new byte[1024];

            //Start Connect
            _connectDone.Reset();
            watch.Start();
            _client.BeginConnect(ControllerIPAddress, ControllerPort, new AsyncCallback(ConnectCallback), _client);
            //wait 2s
            _connectDone.WaitOne(2000, false);

            var text = (_client.Connected) ? "ok" : "ng";
            richTextBox1.AppendText(text + "\r\n");
            watch.Stop();
            richTextBox1.AppendText("Consumer time: " + watch.ElapsedMilliseconds + "\r\n");
        }
开发者ID:Joncash,项目名称:HanboAOMClassLibrary,代码行数:27,代码来源:AsyncConnectionForm.cs

示例2: btnVector_Click

        /// <summary>
        /// Tests for Vektor class
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnVector_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            txtVector.Text = "Starting test suite for the Vektor class.\r\n\r\n";

            // Sample data
            List<Eksam.Vektor> vectors = new List<Vektor>{
                new Vektor(),
                new Vektor(1,1),
                new Vektor(0,1),
                new Vektor(2.2, 1.2),
                new Vektor(10,-4),
                null
            };

            // Go over all defined operations and input combinations
            foreach (Vektor vector in vectors)
            {
                foreach (Vektor secondVector in vectors)
                {
                    txtVector.Text += vector + " + " + secondVector + " = " + (vector + secondVector) + "\r\n";
                    txtVector.Text += vector + " - " + secondVector + " = " + (vector - secondVector) + "\r\n";
                    txtVector.Text += vector + " == " + secondVector + " ... " + (vector == secondVector) + "\r\n";
                    txtVector.Text += vector + vector + " (length " + (vector == null ? 0 : vector.Length()) + ") > " + secondVector + " (length " + (secondVector == null ? 0 : secondVector.Length()) + ")" + " ... " + (vector > secondVector) + "\r\n";
                    txtVector.Text += vector + vector + " (length " + (vector == null ? 0 : vector.Length()) + ") < " + secondVector + " (length " + (secondVector == null ? 0 : secondVector.Length()) + ")" + " ... " + (vector < secondVector) + "\r\n";
                }
            }

            watch.Stop();
            double elapsed = watch.ElapsedMilliseconds;
            txtVector.Text += "\r\nTest suite finished, time elapsed: " + elapsed + "ms.";
        }
开发者ID:anroots,项目名称:ITK-projects,代码行数:38,代码来源:MainWindow.xaml.cs

示例3: MainWindow

        public MainWindow()
        {
            InitializeComponent();
             double ticks = 0L;
             System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

             int frameCount = 0;

             //There is a textbox "txtTicks" which accept a millisecond value
             //And a button "btn", by clicking the button the dispatchertimer &
             //stopwatcher are started.
             _timer.Tick += (sender, e) =>
             {
            frameCount++;
            //System.Diagnostics.Debug.WriteLine(watch.ElapsedMilliseconds);
            if (watch.ElapsedMilliseconds > 1000)
            {
               _timer.Stop();
               watch.Reset();
               MessageBox.Show(string.Format("Already 1 second! FrameCount: {0}", frameCount));
               frameCount = 0;
            }
             };

             this.btn.Click += (sender, e) =>
             {
            double.TryParse(this.txtTicks.Text, out ticks);
            if (ticks != 0.0)
            {
               _timer.Interval = TimeSpan.FromMilliseconds(ticks);
            }
            _timer.Start();
            watch.Start();
             };
        }
开发者ID:fatbigbright,项目名称:CSharpDemos,代码行数:35,代码来源:MainWindow.xaml.cs

示例4: CountWords

        public void CountWords()
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            if (!string.IsNullOrWhiteSpace(this.Text))
            {
                var allWords = this.Text.Split(new string[] { SPACE, NEW_LINE, TAB, CARRIEGE_RETURN, DOT, SEMI_COLON, COLON, TWO_POINT }, StringSplitOptions.RemoveEmptyEntries);
                if (!this.DetailedStats)
                {
                    this.NumberOfWords = allWords.LongLength;
                }
                else
                {
                    for (long cursor = 0; cursor < allWords.LongLength; ++cursor)
                    {
                        if (!string.IsNullOrWhiteSpace(allWords[cursor]))
                        {
                            ++this.NumberOfWords;
                            if (!this.Stats.ContainsKey(allWords[cursor]))
                            {
                                this.Stats[allWords[cursor]] = 1;

                            }
                            else
                            {
                                ++this.Stats[allWords[cursor]];
                            }
                        }
                    }
                }
            }
            watch.Stop();
            this.CountTime = watch.ElapsedMilliseconds;
        }
开发者ID:gergob,项目名称:SampleApplications,代码行数:34,代码来源:WordCounter.cs

示例5: acceptIncomingConnection

        static void acceptIncomingConnection(IAsyncResult ar)
        {
            Socket mainsock = (Socket)ar.AsyncState;
            Socket incomingsock = mainsock.EndAccept(ar);
            Donify.Set();

            System.Diagnostics.Stopwatch swatch = new System.Diagnostics.Stopwatch();
            swatch.Start();

            logger.log("Got connection from: " + incomingsock.RemoteEndPoint, Logging.Priority.Notice);
            if (socketfunctions.waitfordata(incomingsock, 10000, true))
            {
                string[] incomingstring = socketfunctions.receivestring(incomingsock, true).Replace("\r\n", "\n").Split('\n');
                try
                {
                    string response = bstuff.OnyEvents.NewMessage(incomingstring, (IPEndPoint)incomingsock.RemoteEndPoint);
                    logger.log("got from plugins: " + response, Logging.Priority.Notice);
                    if (response == null || response == "")
                        socketfunctions.sendstring(incomingsock, "Blargh.");
                    else
                        socketfunctions.sendstring(incomingsock, response);
                }
                catch (Exception ex)
                { logger.logerror(ex); }

                incomingsock.Shutdown(SocketShutdown.Both);
                incomingsock.Close();

                swatch.Stop();

                logger.log("Session time: " + swatch.ElapsedMilliseconds, Logging.Priority.Info);

                bstuff.OnyVariables.amountloops++;
            }
        }
开发者ID:xarinatan,项目名称:Onymity,代码行数:35,代码来源:Program.cs

示例6: Block

		static Block ()
		{
#if !MF_FRAMEWORK_VERSION_V4_3
			sw = new System.Diagnostics.Stopwatch ();
			sw.Start ();
#endif
		}
开发者ID:Roddoric,项目名称:Monkey.Robotics,代码行数:7,代码来源:Block.cs

示例7: AsyncHTTPSICmd

        public void AsyncHTTPSICmd()
        {
            FileStream stream;
            stream = File.Create(outputFileHTTPSAsync);
            results = new StreamWriter(stream);
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();

            ICmd validICmd = new ICmd(TestGlobals.testServer, TestGlobals.validSerial);
            Test validTest = new Test(validICmd);
            validTest.setTestName("ValidSerial");
            validTest.setExpectedResult ("200");
            validTest.setType ("performance");
            List<Test> tests = new List<Test>();
            tests.Add(validTest);

            // Construct started tasks
            Task<double>[] tasks = new Task<double>[TestGlobals.maxReps];
            for (int i = 0; i < TestGlobals.maxReps; i++)
            {
                System.Threading.Thread.Sleep(TestGlobals.delay);
                tasks[i] = new HTTPSCalls().runTest(validTest, HTTPOperation.GET);
                Console.WriteLine("Test starting:" + i.ToString());
            }
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("All tests initialized, waiting on them to run as async");
            Console.WriteLine("------------------------------------------------------");
            Task.WaitAll(tasks);

            foreach (Task<double> nextResult in tasks)
            {
                results.WriteLine("Test Time," + nextResult.Result);
            }

            results.Close();
        }
开发者ID:Cozumo,项目名称:InterceptorDemoScan,代码行数:35,代码来源:ICmdPerformanceTest.cs

示例8: LoadDatafromAHRS

        private void LoadDatafromAHRS()
        {
            updateTimer.Enabled = false;
            try
            {
                System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
                watch.Start();
                UAVParameter speedparam = (UAVParameter)GPS["lbRMCSpeed"];
                UAVParameter altparam = (UAVParameter)GPS["lbGGAAltitude"];
                UAVParameter phiparam = (UAVParameter)AHRS["phi"];
                UAVParameter thetaparam = (UAVParameter)AHRS["theta"];
                UAVParameter psiparam = (UAVParameter)AHRS["psi"];

                    if (speedparam != null) if (!speedparam.Value.Equals("N/A")) airSpeedIndicator.SetAirSpeedIndicatorParameters(Convert.ToInt32(speedparam.Value));
                    if ((thetaparam != null) && (phiparam != null)) attitudeIndicator.SetAttitudeIndicatorParameters(Convert.ToDouble(thetaparam.Value), Convert.ToDouble(phiparam.Value));
                // Änderungsrate berechnen
                // Turn Quality berechnen
                // this.vspeed = vspeed + Convert.ToInt32(mycore.currentUAV.uavData["lbGGAAltitude"].Value)*0.9;
                    if ((psiparam != null) && (psiparam != null)) this.Compass.SetHeadingIndicatorParameters(Convert.ToInt32(Convert.ToDouble(psiparam.Value)));
                //  if (mycore.currentUAV.uavData.ContainsKey("yaw")) Compass.SetHeadingIndicatorParameters(Convert.ToInt32(mycore.currentUAV.uavData["yaw"].Value));
               //     if (mycore.currentUAV.uavData.ContainsKey("vspeed")) verticalSpeedIndicator.SetVerticalSpeedIndicatorParameters(Convert.ToInt32(mycore.currentUAV.uavData["vspeed"].Value));
                if (altparam != null) altimeter.SetAlimeterParameters(Convert.ToInt32(Convert.ToDouble(altparam.Value)));
            //    if (mycore.currentUAV.uavData.ContainsKey("turnrate") && mycore.currentUAV.uavData.ContainsKey("turnquality")) turnCoordinator.SetTurnCoordinatorParameters(Convert.ToSingle(mycore.currentUAV.uavData["turnrate"].Value), Convert.ToSingle(mycore.currentUAV.uavData["turnquality"].Value));
                this.Invalidate();
                Console.WriteLine("time update:"+watch.ElapsedMilliseconds);
                watch.Stop();
            }
            catch (Exception ex) {

            }
            updateTimer.Enabled = true;
        }
开发者ID:siegelpeter,项目名称:UAV-NET,代码行数:32,代码来源:InstrumentPanel.cs

示例9: BodyForm

 public BodyForm()
 {
     InitializeComponent();
     i = 0;
     UnNum = 0;
     Time = new System.Diagnostics.Stopwatch();
 }
开发者ID:1extra,项目名称:prog2015,代码行数:7,代码来源:BodyForm.cs

示例10: Given_A_Checklist_Is_Being_Saved_Then_Returns_Status_OK

        public void Given_A_Checklist_Is_Being_Saved_Then_Returns_Status_OK()
        {
            // Given
            var client = new RestClient(Url.AbsoluteUri);
            client.Authenticator = new NtlmAuthenticator( "continuous.int","is74rb80pk52" );

            const int numberOfRequestsToSend = 15;
            var stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();
            var parallelLoopResult = Parallel.For(0, numberOfRequestsToSend, x =>
                                                                                 {
                                                                                     //GIVEN
                                                                                     var model = CreateChecklistViewModel();
                                                                                     var resourceUrl = string.Format("{0}{1}/{2}", ApiBaseUrl, "checklists", model.Id.ToString());
                                                                                     var request = new RestRequest(resourceUrl);
                                                                                     request.AddHeader("Content-Type", "application/json");
                                                                                     request.RequestFormat = DataFormat.Json;
                                                                                     request.Method = Method.POST;
                                                                                     request.AddBody(model);

                                                                                     // When
                                                                                     var response = client.Execute(request);

                                                                                     //THEN
                                                                                     Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                                                                                 });

            stopWatch.Stop();

            var processingSeconds = TimeSpan.FromMilliseconds(stopWatch.ElapsedMilliseconds).TotalSeconds;
            Assert.That(parallelLoopResult.IsCompleted);
            Console.WriteLine(string.Format("average: {0}", processingSeconds / numberOfRequestsToSend));
        }
开发者ID:mnasif786,项目名称:Business-Safe,代码行数:33,代码来源:PostChecklist.cs

示例11: Renard

        public Renard(string portName)
        {
            this.serialPort = new SerialPort(portName, 57600);
            this.renardData = new byte[24];

            this.cancelSource = new System.Threading.CancellationTokenSource();
            this.firstChange = new System.Diagnostics.Stopwatch();

            this.senderTask = new Task(x =>
                {
                    while (!this.cancelSource.IsCancellationRequested)
                    {
                        bool sentChanges = false;

                        lock (lockObject)
                        {
                            if (this.dataChanges > 0)
                            {
                                this.firstChange.Stop();
                                //log.Info("Sending {0} changes to Renard. Oldest {1:N2}ms",
                                //    this.dataChanges, this.firstChange.Elapsed.TotalMilliseconds);
                                this.dataChanges = 0;
                                sentChanges = true;

                                SendSerialData(this.renardData);
                            }
                        }

                        if(!sentChanges)
                            System.Threading.Thread.Sleep(10);
                    }
                }, this.cancelSource.Token, TaskCreationOptions.LongRunning);

            Executor.Current.Register(this);
        }
开发者ID:HakanL,项目名称:animatroller,代码行数:35,代码来源:Renard.cs

示例12: Run

        static void Run(string filename, bool verbose)
        {
            if (!File.Exists(filename))
            {
                Console.WriteLine("Cannot find file " + filename);
                return;
            }

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            var opts = new Options();
            opts.ExecutionMode = ExecutionMode.Serial;
            ProtoCore.Core core = new Core(opts);
            core.Compilers.Add(ProtoCore.Language.Associative, new ProtoAssociative.Compiler(core));
            core.Compilers.Add(ProtoCore.Language.Imperative, new ProtoImperative.Compiler(core));
            core.Options.DumpByteCode = verbose;
            core.Options.Verbose = verbose;
            ProtoFFI.DLLFFIHandler.Register(ProtoFFI.FFILanguage.CSharp, new ProtoFFI.CSModuleHelper());

            ProtoScriptRunner runner = new ProtoScriptRunner();

            runner.LoadAndExecute(filename, core);
            long ms = sw.ElapsedMilliseconds;
            sw.Stop();
            Console.WriteLine(ms);
        }
开发者ID:ankushraizada,项目名称:Dynamo,代码行数:27,代码来源:Program.cs

示例13: DevRun

        static void DevRun()
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();


            var opts = new Options();
            opts.ExecutionMode = ExecutionMode.Serial;
            ProtoCore.Core core = new Core(opts);
            core.Compilers.Add(ProtoCore.Language.Associative, new ProtoAssociative.Compiler(core));
            core.Compilers.Add(ProtoCore.Language.Imperative, new ProtoImperative.Compiler(core));
#if DEBUG
            core.Options.DumpByteCode = true;
            core.Options.Verbose = true;
#else
            core.Options.DumpByteCode = false;
            core.Options.Verbose = false;
#endif
            ProtoFFI.DLLFFIHandler.Register(ProtoFFI.FFILanguage.CSharp, new ProtoFFI.CSModuleHelper());
            ProtoScriptRunner runner = new ProtoScriptRunner();

            // Assuming current directory in test/debug mode is "...\Dynamo\bin\AnyCPU\Debug"
            runner.LoadAndExecute(@"..\..\..\test\core\dsevaluation\DSFiles\test.ds", core);

            long ms = sw.ElapsedMilliseconds;
            sw.Stop();
            Console.WriteLine(ms);
            Console.ReadLine();
        }
开发者ID:ankushraizada,项目名称:Dynamo,代码行数:29,代码来源:Program.cs

示例14: Main

        static void Main(string[] args)
        {
            var stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();

            Action<CancellationToken> longRunning = async (token) =>
            {
                for (int i = 0; i < 100; i++)
                {
                    Console.WriteLine("{0} {1}", i, stopwatch.Elapsed.TotalMilliseconds); 
                    await Task.Delay(new Random().Next(3, 100));
                    if (token.IsCancellationRequested)
                        break;
                }
            };

            // start with cancel option
            var source = new CancellationTokenSource();
            longRunning.Invoke(source.Token);

            // wait for a second 
            Thread.Sleep(1000);

            // top processing
            source.Cancel();

            Console.Read();
        }
开发者ID:noriike,项目名称:xaml-106136,代码行数:28,代码来源:Program.cs

示例15: MINIMAX_DECISION

        public int MINIMAX_DECISION(Game game)
        {
            _stopwatch = new System.Diagnostics.Stopwatch();
            _stopwatch.Start();

            int maxValue = int.MinValue;
            List<int> colOptions = new List<int>();

            List<int> actions = ACTIONS(game);
            int iterationCounter = 0;
            foreach (int column in actions)
            {
                iterationCounter++;
                int v = MIN_VALUE(RESULT(game, column, _max), 1);

                if (v > maxValue)
                {
                    maxValue = v;
                    colOptions.Clear();
                    colOptions.Add(column);
                }
                else if (v == maxValue)
                {
                    colOptions.Add(column);
                }

                if (_stopwatch.Elapsed.Seconds > (game.TimeLimitSeconds - 1)) break;
            }

            int c = colOptions[_rnd.Next(colOptions.Count)];
            Console.WriteLine("Column selection: {0} / Elapsed: {1} / Total Actions: {2} / Actions Evaluated: {3}", c, _stopwatch.Elapsed, actions.Count, iterationCounter);
            return c;
        }
开发者ID:rickhaffey,项目名称:CSC480,代码行数:33,代码来源:Minimax.cs


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