System.Diagnostics.Stopwatch.Reset()

Here are the examples of the csharp api System.Diagnostics.Stopwatch.Reset() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

662 Examples 7

19 View Source File : LoadBalancedQueue.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

public void Update()
        {
            if (!_queue.hasNext)
            {
                return;
            }

            var now = _time();
            _watch.Reset();
            _watch.Start();

            var maxUpdates = this.maxUpdatesPerInterval;
            int updateCount = 0;
            float overDue = 0.0f;

            if (autoAdjust)
            {
                var framesPerInterval = this.defaultUpdateInterval / _deltaTime();
                maxUpdates = Mathf.CeilToInt(_queue.count / framesPerInterval);
            }

            var item = _queue.Peek();
            while ((updateCount++ < maxUpdates) && (item.nextUpdate <= now) && (this.autoAdjust || (_watch.ElapsedMilliseconds < this.maxUpdateTimeInMillisecondsPerUpdate)))
            {
                var deltaTime = now - item.lastUpdate;
                overDue += (deltaTime - item.interval);

                var nextInterval = item.item.ExecuteUpdate(deltaTime, item.interval).GetValueOrDefault(item.interval);

                if (item.item.repeat)
                {
                    //Next interval is the suggested interval or the default. It cannot be 0 since that would lead to continuous updates in this loop.
                    nextInterval = Mathf.Max(nextInterval, 0.01f);

                    item.lastUpdate = now;
                    item.nextUpdate = now + nextInterval;
                    _queue.ReheapifyDownFrom(0);
                }
                else
                {
                    var lbi = _queue.Remove();
                    lbi.Dispose();
                }

                if (!_queue.hasNext)
                {
                    break;
                }

                item = _queue.Peek();
            }

            this.updatedItemsCount = updateCount - 1;
            this.updatesOverdueByTotal = overDue;
            this.updateMillisecondsUsed = _watch.ElapsedMilliseconds;
        }

19 View Source File : Timer.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d

public void Reset()
        {
            // reset by restarting the timer
            this._timer.Reset();
            this._timer.Start();
        }

19 View Source File : MapboxUnitTests_SQLiteCache.cs
License : MIT License
Project Creator : alen-smajic

private List<long> simpleInsert(string tileSetName, bool forceInsert, HashSet<CanonicalTileId> tileIds = null, int itemCount = 1000)
		{
			if (null != tileIds) { itemCount = tileIds.Count; }

			List<long> elapsed = new List<long>();
			Stopwatch sw = new Stopwatch();

			for (int i = 0; i < itemCount; i++)
			{
				CanonicalTileId tileId = null != tileIds ? tileIds.ElementAt(i) : new CanonicalTileId(0, 0, 0);
				DateTime now = DateTime.UtcNow;
				CacheItem cacheItem = new CacheItem()
				{
					AddedToCacheTicksUtc = now.Ticks,
					// simulate 100KB data
					Data = Enumerable.Repeat((byte)0x58, 100 * 1024).ToArray(),
					ETag = "etag",
					LastModified = now
				};

				sw.Start();
				_cache.Add(tileSetName, tileId, cacheItem, forceInsert);
				sw.Stop();
				elapsed.Add(sw.ElapsedMilliseconds);
				sw.Reset();
			}

			return elapsed;
		}

19 View Source File : DownloaderViewModel.cs
License : GNU General Public License v3.0
Project Creator : antikmozib

private void StartReportingSpeed()
        {
            if (_semapreplacedMeasuringSpeed.CurrentCount == 0) return;

            Task.Run(async () =>
            {
                await _semapreplacedMeasuringSpeed.WaitAsync();
                var stopWatch = new Stopwatch();
                long bytesFrom;
                long bytesTo;
                long bytesCaptured;
                do
                {
                    bytesFrom = 0;
                    bytesTo = 0;
                    stopWatch.Start();
                    bytesFrom = this.BytesDownloaded;
                    await Task.Delay(1000);
                    bytesTo = this.BytesDownloaded;
                    stopWatch.Stop();
                    bytesCaptured = bytesTo - bytesFrom;
                    if (bytesCaptured >= 0 && stopWatch.ElapsedMilliseconds > 0)
                    {
                        this.Speed = (long)((double)bytesCaptured / ((double)stopWatch.ElapsedMilliseconds / 1000));
                        RaisePropertyChanged(nameof(this.Speed));
                        RaisePropertyChanged(nameof(this.BytesDownloaded));
                    }
                    stopWatch.Reset();
                } while (bytesCaptured > 0);
                this.Speed = null;
                RaisePropertyChanged(nameof(this.Speed));
                _semapreplacedMeasuringSpeed.Release();
            });
        }

19 View Source File : Benchmark.cs
License : Apache License 2.0
Project Creator : alexyakunin

private void RunOnce()
        {
            if (MustWarmup) {
                Action.Invoke(true);
                SubtractAction?.Invoke(true);
                MustWarmup = false;
            }
            if (MustGC)
                GC.Collect();

            var elapsed = TimeSpan.Zero;
            
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            try {
                Action.Invoke(false);
            }
            finally {
                stopwatch.Stop();
                elapsed += stopwatch.Elapsed;
            }

            if (SubtractAction != null) {
                if (MustGC)
                    GC.Collect();
                stopwatch.Reset();
                stopwatch.Start();
                try {
                    SubtractAction.Invoke(false);
                }
                finally {
                    stopwatch.Stop();
                    elapsed -= stopwatch.Elapsed * SubtractActionFactor;
                }
            }

            Timings.Add(elapsed);
        }

19 View Source File : Island.cs
License : MIT License
Project Creator : Alan-FGR

public void Solve(ref TimeStep step, ref Vector2 gravity)
        {
            float h = step.dt;

            // Integrate velocities and apply damping. Initialize the body state.
            for (int i = 0; i < BodyCount; ++i)
            {
                Body b = Bodies[i];

                Vector2 c = b._sweep.C;
                float a = b._sweep.A;
                Vector2 v = b._linearVelocity;
                float w = b._angularVelocity;

                // Store positions for continuous collision.
                b._sweep.C0 = b._sweep.C;
                b._sweep.A0 = b._sweep.A;

                if (b.BodyType == BodyType.Dynamic)
                {
                    // Integrate velocities.

                    // FPE: Only apply gravity if the body wants it.
                    if (b.IgnoreGravity)
                        v += h * (b._invMreplaced * b._force);
                    else
                        v += h * (b.GravityScale * gravity + b._invMreplaced * b._force);

                    w += h * b._invI * b._torque;

                    // Apply damping.
                    // ODE: dv/dt + c * v = 0
                    // Solution: v(t) = v0 * exp(-c * t)
                    // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt)
                    // v2 = exp(-c * dt) * v1
                    // Taylor expansion:
                    // v2 = (1.0f - c * dt) * v1
                    v *= MathUtils.Clamp(1.0f - h * b.LinearDamping, 0.0f, 1.0f);
                    w *= MathUtils.Clamp(1.0f - h * b.AngularDamping, 0.0f, 1.0f);
                }

                _positions[i].c = c;
                _positions[i].a = a;
                _velocities[i].v = v;
                _velocities[i].w = w;
            }

            // Solver data
            SolverData solverData = new SolverData();
            solverData.step = step;
            solverData.positions = _positions;
            solverData.velocities = _velocities;

            _contactSolver.Reset(step, ContactCount, _contacts, _positions, _velocities);
            _contactSolver.InitializeVelocityConstraints();

            if (Settings.EnableWarmstarting)
            {
                _contactSolver.WarmStart();
            }

            if (Settings.EnableDiagnostics)
                _watch.Start();

            for (int i = 0; i < JointCount; ++i)
            {
                if (_joints[i].Enabled)
                    _joints[i].InitVelocityConstraints(ref solverData);
            }

            if (Settings.EnableDiagnostics)
                _watch.Stop();

            // Solve velocity constraints.
            for (int i = 0; i < Settings.VelocityIterations; ++i)
            {
                for (int j = 0; j < JointCount; ++j)
                {
                    Joint joint = _joints[j];

                    if (!joint.Enabled)
                        continue;

                    if (Settings.EnableDiagnostics)
                        _watch.Start();

                    joint.SolveVelocityConstraints(ref solverData);
                    joint.Validate(step.inv_dt);

                    if (Settings.EnableDiagnostics)
                        _watch.Stop();
                }

                _contactSolver.SolveVelocityConstraints();
            }

            // Store impulses for warm starting.
            _contactSolver.StoreImpulses();

            // Integrate positions
            for (int i = 0; i < BodyCount; ++i)
            {
                Vector2 c = _positions[i].c;
                float a = _positions[i].a;
                Vector2 v = _velocities[i].v;
                float w = _velocities[i].w;

                // Check for large velocities
                Vector2 translation = h * v;
                if (Vector2.Dot(translation, translation) > Settings.MaxTranslationSquared)
                {
                    float ratio = Settings.MaxTranslation / translation.Length();
                    v *= ratio;
                }

                float rotation = h * w;
                if (rotation * rotation > Settings.MaxRotationSquared)
                {
                    float ratio = Settings.MaxRotation / Math.Abs(rotation);
                    w *= ratio;
                }

                // Integrate
                c += h * v;
                a += h * w;

                _positions[i].c = c;
                _positions[i].a = a;
                _velocities[i].v = v;
                _velocities[i].w = w;
            }


            // Solve position constraints
            bool positionSolved = false;
            for (int i = 0; i < Settings.PositionIterations; ++i)
            {
                bool contactsOkay = _contactSolver.SolvePositionConstraints();

                bool jointsOkay = true;
                for (int j = 0; j < JointCount; ++j)
                {
                    Joint joint = _joints[j];

                    if (!joint.Enabled)
                        continue;

                    if (Settings.EnableDiagnostics)
                        _watch.Start();

                    bool jointOkay = joint.SolvePositionConstraints(ref solverData);

                    if (Settings.EnableDiagnostics)
                        _watch.Stop();

                    jointsOkay = jointsOkay && jointOkay;
                }

                if (contactsOkay && jointsOkay)
                {
                    // Exit early if the position errors are small.
                    positionSolved = true;
                    break;
                }
            }

            if (Settings.EnableDiagnostics)
            {
                JointUpdateTime = _watch.ElapsedTicks;
                _watch.Reset();
            }

            // Copy state buffers back to the bodies
            for (int i = 0; i < BodyCount; ++i)
            {
                Body body = Bodies[i];
                body._sweep.C = _positions[i].c;
                body._sweep.A = _positions[i].a;
                body._linearVelocity = _velocities[i].v;
                body._angularVelocity = _velocities[i].w;
                body.SynchronizeTransform();
            }

            Report(_contactSolver._velocityConstraints);

            if (Settings.AllowSleep)
            {
                float minSleepTime = Settings.MaxFloat;

                for (int i = 0; i < BodyCount; ++i)
                {
                    Body b = Bodies[i];

                    if (b.BodyType == BodyType.Static)
                        continue;

                    if (!b.SleepingAllowed || b._angularVelocity * b._angularVelocity > AngTolSqr || Vector2.Dot(b._linearVelocity, b._linearVelocity) > LinTolSqr)
                    {
                        b._sleepTime = 0.0f;
                        minSleepTime = 0.0f;
                    }
                    else
                    {
                        b._sleepTime += h;
                        minSleepTime = Math.Min(minSleepTime, b._sleepTime);
                    }
                }

                if (minSleepTime >= Settings.TimeToSleep && positionSolved)
                {
                    for (int i = 0; i < BodyCount; ++i)
                    {
                        Body b = Bodies[i];
                        b.Awake = false;
                    }
                }
            }
        }

19 View Source File : RegionHandler.cs
License : MIT License
Project Creator : ArcturusZhang

protected internal bool RegionPingThreaded()
        {
            this.region.Ping = PingWhenFailed;

            float rttSum = 0.0f;
            int replyCount = 0;


            Stopwatch sw = new Stopwatch();
            for (this.CurrentAttempt = 0; this.CurrentAttempt < Attempts; this.CurrentAttempt++)
            {
                bool overtime = false;
                sw.Reset();
                sw.Start();

                try
                {
                    this.ping.StartPing(this.regionAddress);
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine("RegionPinger.RegionPingThreaded() catched an exception for ping.StartPing(). Exception: " + e + " Source: " + e.Source + " Message: " + e.Message);
                    break;
                }


                while (!this.ping.Done())
                {
                    if (sw.ElapsedMilliseconds >= MaxMilliseconsPerPing)
                    {
                        overtime = true;
                        break;
                    }
                    #if !NETFX_CORE
                    System.Threading.Thread.Sleep(0);
                    #endif
                }


                sw.Stop();
                int rtt = (int)sw.ElapsedMilliseconds;

                if (IgnoreInitialAttempt && this.CurrentAttempt == 0)
                {
                    // do nothing.
                }
                else if (this.ping.Successful && !overtime)
                {
                    rttSum += rtt;
                    replyCount++;
                    this.region.Ping = (int)((rttSum) / replyCount);
                }

                #if !NETFX_CORE
                System.Threading.Thread.Sleep(10);
                #endif
            }

            this.Done = true;
            this.ping.Dispose();

            this.onDoneCall(this.region);

            return false;
        }

19 View Source File : ChatBoxViewModel.cs
License : MIT License
Project Creator : AFei19911012

private void StartRecord()
        {
            ExternDllHelper.MciSendString("set wave bitpersample 8", "", 0, 0);
            ExternDllHelper.MciSendString("set wave samplespersec 20000", "", 0, 0);
            ExternDllHelper.MciSendString("set wave channels 2", "", 0, 0);
            ExternDllHelper.MciSendString("set wave format tag pcm", "", 0, 0);
            ExternDllHelper.MciSendString("open new type WAVEAudio alias movie", "", 0, 0);
            ExternDllHelper.MciSendString("record movie", "", 0, 0);

            _stopwatch.Reset();
            _stopwatch.Start();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : Azure-Samples

public void Run(CloudTableClient tableClient, int numIterations, Boolean useAzureTablestorage)
        {
            Console.WriteLine("Creating Table if it doesn't exist...");
            
            CloudTable table = tableClient.GetTableReference("people");
            if (useAzureTablestorage) {
                table.CreateIfNotExists();
            } else
            {
                // Azure Cosmos DB supports a reserved throughput model. You can configure the default throughput per table by 
                // configuring the AppSetting for "TableThroughput" in terms of RU (request units) per second. 1 RU = 1 read of a 1KB doreplacedent.
                // All operations are expressed in terms of RUs based on their CPU, memory, and IOPS consumption.
                // The number of RUs to be used by the table can be submitted as an argument here.
                table.CreateIfNotExists(throughput: 400);
            }

            List<CustomerEnreplacedy> items = new List<CustomerEnreplacedy>();
            List<double> latencies = new List<double>();
            Stopwatch watch = new Stopwatch();

            Console.WriteLine("Running inserts: ");
            for (int i = 0; i < numIterations; i++)
            {
                watch.Start();

                CustomerEnreplacedy item = new CustomerEnreplacedy()
                {
                    ParreplacedionKey = Guid.NewGuid().ToString(),
                    RowKey = Guid.NewGuid().ToString(),
                    Email = $"{GetRandomString(6)}@contoso.com",
                    PhoneNumber = "425-555-0102",
                    Bio = GetRandomString(1000)
                };
                
                // Azure Cosmos DB is designed for guaranteed low latency at any scale, across the world
                // Writes in Azure Cosmos DB complete <10ms at p99 and ~6ms at p50. These are sychronously replicated, 
                // durably committed, and all content indexed. 
                // Latency is for reads for app in the same region as one of the Azure Cosmos DB regions
                // When the Table API is generally available, these latency guarantees are backed by SLAs
                TableOperation insertOperation = TableOperation.Insert(item);
                table.Execute(insertOperation);
                double latencyInMs = watch.Elapsed.TotalMilliseconds;

                Console.Write($"\r\tInsert #{i + 1} completed in {latencyInMs} ms.");
                items.Add(item);
                latencies.Add(latencyInMs);

                watch.Reset();
            }

            latencies.Sort();
            Console.WriteLine($"\n\tp0:{latencies[0]}, p50: {latencies[(int)(numIterations * 0.50)]}, p90: {latencies[(int)(numIterations * 0.90)]}. p99: {latencies[(int)(numIterations * 0.99)]}");
            Console.WriteLine("\n");

            Console.WriteLine("Running retrieves: ");
            latencies.Clear();

            for (int i = 0; i < numIterations; i++)
            {
                watch.Start();

                // Retrieves in Azure Cosmos DB complete <10ms at p99 and ~1ms at p50.
                // Latency is for reads for app in the same region as one of the Azure Cosmos DB regions
                // When the Table API is generally available, these latency guarantees are backed by SLAs
                TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEnreplacedy>(items[i].ParreplacedionKey, items[i].RowKey);
                table.Execute(retrieveOperation);
                double latencyInMs = watch.Elapsed.TotalMilliseconds;

                Console.Write($"\r\tRetrieve #{i + 1} completed in {latencyInMs} ms");
                latencies.Add(latencyInMs);

                watch.Reset();
            }

            latencies.Sort();
            Console.WriteLine($"\n\tp0:{latencies[0]}, p50: {latencies[(int)(numIterations * 0.50)]}, p90: {latencies[(int)(numIterations * 0.90)]}. p99: {latencies[(int)(numIterations * 0.99)]}");
            Console.WriteLine("\n");

            Console.WriteLine("Running query against secondary index: ");
            latencies.Clear();

            for (int i = 0; i < numIterations; i++)
            {
                watch.Start();

                // Query against any property using the index. Since Azure Cosmos DB supports automatic secondary indexes,
                // This query completes within milliseconds. The query performance difference is much more pronounced when you 
                // have 1000s-millions of doreplacedents.
                TableQuery<CustomerEnreplacedy> rangeQuery = new TableQuery<CustomerEnreplacedy>().Where(
                    TableQuery.GenerateFilterCondition("Email", QueryComparisons.Equal, items[i].Email));

                int count = 0;
                foreach (CustomerEnreplacedy enreplacedy in table.ExecuteQuery(rangeQuery))
                {
                    // Process query results
                    count++;
                }

                double latencyInMs = watch.Elapsed.TotalMilliseconds;
                Console.Write($"\r\tQuery #{i + 1} completed in {latencyInMs} ms");
                latencies.Add(latencyInMs);

                watch.Reset();
            }

            latencies.Sort();
            Console.WriteLine($"\n\tp0:{latencies[0]}, p50: {latencies[(int)(numIterations * 0.50)]}, p90: {latencies[(int)(numIterations * 0.90)]}. p99: {latencies[(int)(numIterations * 0.99)]}");
            Console.WriteLine("\n");

            Console.WriteLine("Running replace: ");
            latencies.Clear();

            for (int i = 0; i < numIterations; i++)
            {
                watch.Start();

                // Same latency as inserts, p99 < 15ms, and p50 < 6ms
                items[i].PhoneNumber = "425-555-5555";
                TableOperation replaceOperation = TableOperation.Replace(items[i]);
                table.Execute(replaceOperation);

                double latencyInMs = watch.Elapsed.TotalMilliseconds;
                Console.Write($"\r\tReplace #{i + 1} completed in {latencyInMs} ms");
                latencies.Add(latencyInMs);

                watch.Reset();
            }

            latencies.Sort();
            Console.WriteLine($"\n\tp0:{latencies[0]}, p50: {latencies[(int)(numIterations * 0.50)]}, p90: {latencies[(int)(numIterations * 0.90)]}. p99: {latencies[(int)(numIterations * 0.99)]}");
            Console.WriteLine("\n");

            #region DeleteTable
            Console.WriteLine("Running deletes: ");
            latencies.Clear();

            for (int i = 0; i < numIterations; i++)
            {
                watch.Start();

                // Same latency as inserts, p99 < 15ms, and p50 < 6ms
                TableOperation deleteOperation = TableOperation.Delete(items[i]);
                table.Execute(deleteOperation);

                double latencyInMs = watch.Elapsed.TotalMilliseconds;
                Console.Write($"\r\tDelete #{i + 1} completed in {latencyInMs} ms");
                latencies.Add(latencyInMs);

                watch.Reset();
            }

            latencies.Sort();
            Console.WriteLine($"\n\tp0:{latencies[0]}, p50: {latencies[(int)(numIterations * 0.50)]}, p90: {latencies[(int)(numIterations * 0.90)]}. p99: {latencies[(int)(numIterations * 0.99)]}");
            Console.WriteLine("\n");
            #endregion

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }

19 View Source File : Startup.cs
License : MIT License
Project Creator : ahydrax

public static void CpuKill(int cpuUsage)
        {
            Parallel.For(0, 1, i =>
            {
                var w1 = Stopwatch.StartNew();
                var w2 = Stopwatch.StartNew();

                while (true)
                {
                    if (w2.ElapsedMilliseconds > cpuUsage)
                    {
                        Thread.Sleep(100 - cpuUsage);
                        w2.Reset();
                        w2.Start();
                    }

                    if (w1.Elapsed > TimeSpan.FromSeconds(15))
                    {
                        break;
                    }
                }
            });
        }

19 View Source File : Worker.cs
License : MIT License
Project Creator : AndrewBabbitt97

private void Api_ColorChanged(object sender, RzChromaBroadcastColorChangedEventArgs e)
        {
            var currentColor = 0;

            foreach (var deviceProvider in _rgbKit.DeviceProviders)
            {
                foreach (var device in deviceProvider.Devices)
                {
                    foreach (var light in device.Lights)
                    {
                        light.Color = e.Colors[currentColor];
                        currentColor++;

                        if (currentColor == e.Colors.Length)
                            currentColor = 0;
                    }

                    if (_performanceMetricsEnabled)
                    {
                        _performanceMetricsStopwatch.Reset();
                        _performanceMetricsStopwatch.Start();
                    }

                    if (device.Lights.Count() > 0)
                    {
                        device.ApplyLights();
                    }

                    if (_performanceMetricsEnabled)
                    {
                        _performanceMetricsStopwatch.Stop();
                        _logger.LogInformation(new EventId(1, "Metrics"), deviceProvider.Name + " - " + device.Name + ": Took " + _performanceMetricsStopwatch.ElapsedMilliseconds + "ms To Update");
                    }
                }
            }
        }

19 View Source File : IdGeneraterTests.cs
License : MIT License
Project Creator : AlphaYu

[Fact]
        public void TestSpeed()
        {
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();
            Parallel.For(1, 1000000, index =>
            {
                IdGenerater.GetNextId();
            });
            stopwatch.Stop();
            //持续时间: 517 毫秒
            _output.WriteLine(stopwatch.ElapsedMilliseconds.ToString());
            stopwatch.Reset();
        }

19 View Source File : TestLargeAmount.cs
License : MIT License
Project Creator : aillieo

public void AddRandomData()
    {
        DefaultScrollItemData newData = new DefaultScrollItemData() { name = GetRandomSizeString()};
        testData.Insert(UnityEngine.Random.Range(0,testData.Count), newData);

        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        scrollView.UpdateData(true);
        stopwatch.Stop();
        long time1 = stopwatch.ElapsedMilliseconds;
        stopwatch.Reset();
        stopwatch.Start();
        scrollViewEx.UpdateData(true);
        stopwatch.Stop();
        long time2 = stopwatch.ElapsedMilliseconds;
        UnityEngine.Debug.Log($"cost time in ms:     ScrollView:{time1}     ScrollViewEx:{time2}");
    }

19 View Source File : LongRunningAction.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

public float? ExecuteUpdate(float deltaTime, float nextInterval)
        {
            if (_iter == null)
            {
                _iter = _action();
            }

            bool moreWork = true;
            _watch.Reset();
            _watch.Start();
            while (moreWork && _watch.ElapsedMilliseconds < _maxMillisecondUsedPerFrame)
            {
                moreWork = _iter.MoveNext();
            }

            this.repeat = moreWork;
            if (!moreWork)
            {
                _iter = null;

                if (_callback != null)
                {
                    _callback();
                }
            }

            return 0f;
        }

19 View Source File : MixedRealityToolkitVisualProfiler.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private void LateUpdate()
        {
            if (window == null)
            {
                return;
            }

            using (LateUpdatePerfMarker.Auto())
            {
                // Update window transformation.
                Transform cameraTransform = CameraCache.Main ? CameraCache.Main.transform : null;

                if (ShouldShowProfiler && cameraTransform != null)
                {
                    float t = Time.deltaTime * windowFollowSpeed;
                    window.position = Vector3.Lerp(window.position, CalculateWindowPosition(cameraTransform), t);
                    window.rotation = Quaternion.Slerp(window.rotation, CalculateWindowRotation(cameraTransform), t);
                    window.localScale = defaultWindowScale * windowScale;
                    CalculateBackgroundSize();
                }

                // Capture frame timings every frame and read from it depending on the frameSampleRate.
                FrameTimingManager.CaptureFrameTimings();

                ++frameCount;
                float elapsedSeconds = stopwatch.ElapsedMilliseconds * 0.001f;

                if (elapsedSeconds >= frameSampleRate)
                {
                    int cpuFrameRate = (int)(1.0f / (elapsedSeconds / frameCount));
                    int gpuFrameRate = 0;

                    // Many platforms do not yet support the FrameTimingManager. When timing data is returned from the FrameTimingManager we will use
                    // its timing data, else we will depend on the stopwatch.
                    uint frameTimingsCount = FrameTimingManager.GetLatestTimings((uint)Mathf.Min(frameCount, maxFrameTimings), frameTimings);

                    if (frameTimingsCount != 0)
                    {
                        float cpuFrameTime, gpuFrameTime;
                        AverageFrameTiming(frameTimings, frameTimingsCount, out cpuFrameTime, out gpuFrameTime);
                        cpuFrameRate = (int)(1.0f / (cpuFrameTime / frameCount));
                        gpuFrameRate = (int)(1.0f / (gpuFrameTime / frameCount));
                    }

                    // Update frame rate text.
                    cpuFrameRateText.text = cpuFrameRateStrings[Mathf.Clamp(cpuFrameRate, 0, maxTargetFrameRate)];

                    if (gpuFrameRate != 0)
                    {
                        gpuFrameRateText.gameObject.SetActive(true);
                        gpuFrameRateText.text = gpuFrameRateStrings[Mathf.Clamp(gpuFrameRate, 0, maxTargetFrameRate)];
                    }

                    // Update frame colors.
                    if (frameInfoVisible)
                    {
                        for (int i = frameRange - 1; i > 0; --i)
                        {
                            frameInfoColors[i] = frameInfoColors[i - 1];
                        }

                        frameInfoColors[0] = CalculateFrameColor(cpuFrameRate);
                        frameInfoPropertyBlock.SetVectorArray(colorID, frameInfoColors);
                    }

                    // Reset timers.
                    frameCount = 0;
                    stopwatch.Reset();
                    stopwatch.Start();
                }

                // Draw frame info.
                if (ShouldShowProfiler && frameInfoVisible)
                {
                    Matrix4x4 parentLocalToWorldMatrix = window.localToWorldMatrix;

                    if (defaultInstancedMaterial != null)
                    {
                        frameInfoPropertyBlock.SetMatrix(parentMatrixID, parentLocalToWorldMatrix);
                        Graphics.DrawMeshInstanced(quadMesh, 0, defaultInstancedMaterial, frameInfoMatrices, frameInfoMatrices.Length, frameInfoPropertyBlock, UnityEngine.Rendering.ShadowCastingMode.Off, false);
                    }
                    else
                    {
                        // If a instanced material is not available, fall back to non-instanced rendering.
                        for (int i = 0; i < frameInfoMatrices.Length; ++i)
                        {
                            frameInfoPropertyBlock.SetColor(colorID, frameInfoColors[i]);
                            Graphics.DrawMesh(quadMesh, parentLocalToWorldMatrix * frameInfoMatrices[i], defaultMaterial, 0, null, 0, frameInfoPropertyBlock, false, false, false);
                        }
                    }
                }

                // Update memory statistics.
                if (ShouldShowProfiler && memoryStatsVisible)
                {
                    ulong limit = AppMemoryUsageLimit;

                    if (limit != limitMemoryUsage)
                    {
                        if (WillDisplayedMemoryUsageDiffer(limitMemoryUsage, limit, displayedDecimalDigits))
                        {
                            MemoryUsageToString(stringBuffer, displayedDecimalDigits, limitMemoryText, limitMemoryString, limit);
                        }

                        limitMemoryUsage = limit;
                    }

                    ulong usage = AppMemoryUsage;

                    if (usage != memoryUsage)
                    {
                        usedAnchor.localScale = new Vector3((float)usage / limitMemoryUsage, usedAnchor.localScale.y, usedAnchor.localScale.z);

                        if (WillDisplayedMemoryUsageDiffer(memoryUsage, usage, displayedDecimalDigits))
                        {
                            MemoryUsageToString(stringBuffer, displayedDecimalDigits, usedMemoryText, usedMemoryString, usage);
                        }

                        memoryUsage = usage;
                    }

                    if (memoryUsage > peakMemoryUsage)
                    {
                        peakAnchor.localScale = new Vector3((float)memoryUsage / limitMemoryUsage, peakAnchor.localScale.y, peakAnchor.localScale.z);

                        if (WillDisplayedMemoryUsageDiffer(peakMemoryUsage, memoryUsage, displayedDecimalDigits))
                        {
                            MemoryUsageToString(stringBuffer, displayedDecimalDigits, peakMemoryText, peakMemoryString, memoryUsage);
                        }

                        peakMemoryUsage = memoryUsage;
                    }
                }

                // Update visibility state.
                window.gameObject.SetActive(ShouldShowProfiler);
                memoryStats.gameObject.SetActive(memoryStatsVisible);
            }
        }

19 View Source File : DebugTimer.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

[Conditional("UNITY_EDITOR")]
        public static void StartAverage(int iterations)
        {
            if (_count <= 0)
            {
                _avg = 0f;
                _iterations = _count = iterations;
                _avgWatch = Stopwatch.StartNew();
            }
            else
            {
                _avgWatch.Reset();
                _avgWatch.Start();
            }
        }

19 View Source File : SpeedChecker.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

private static void ResetAverageSpeedCheck()
        {
            AverageSpeedCheckStopwatch.Reset();
            AverageSpeed = 0f;
            AverageSpeedCheckDistance = 0f;
            AverageSpeedCheckSecondsPreplaceded = 0f;
            MeasuringAverageSpeed = false;
            AverageSpeedCheckerColor = Color.White;
            MeasuringAverageSpeed = false;
        }

19 View Source File : RuntimeGuard.cs
License : MIT License
Project Creator : ashmind

internal void Start(IRuntimeGuardSettings settings) {
            _active = true;

            _stackBytesLimit = settings.StackBytesLimit;
            _stackBytesLimitInExceptionHandlers = settings.StackBytesLimitInExceptionHandlers;
            _allocatedCountTotalLimit = settings.AllocatedCountTotalLimit;

            var timeLimitStopwatchTicks = (long)(settings.TimeLimit.TotalSeconds * Stopwatch.Frequency);
            if (timeLimitStopwatchTicks < 0) // overflow, e.g. with TimeSpan.MaxValue
                timeLimitStopwatchTicks = long.MaxValue;
            _timeLimitStopwatchTicks = timeLimitStopwatchTicks;

            _operationCountLimit = settings.OperationCountLimit;
            _afterForcedDispose = settings.AfterForcedDispose;

            _stackBaseline = 0;
            _operationCount = 0;

            _disposables?.Clear();

            _stopwatch.Stop();
            _stopwatch.Reset();
        }

19 View Source File : JobAnimationCurveTests.cs
License : MIT License
Project Creator : 5argon

private (long mainTicks, long jobTicks) MainThreadPerformanceTest(AnimationCurve ac, int iterationCount)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

            var jac = new JobAnimationCurve(ac, Allocator.Temp);

            float[] evaluated = new float[iterationCount];

            sw.Start();
            for (int i = 0; i < evaluated.Length; i++)
            {
                evaluated[i] = jac.Evaluate(i / (float)iterationCount);
            }
            sw.Stop();
            var jobTicks = sw.ElapsedTicks;

            sw.Reset();

            sw.Start();
            for (int i = 0; i < evaluated.Length; i++)
            {
                evaluated[i] = ac.Evaluate(i / (float)iterationCount);
            }
            sw.Stop();
            var mainTicks = sw.ElapsedTicks;


            jac.Dispose();

            return (mainTicks, jobTicks);
        }

19 View Source File : BSONTestForm.cs
License : MIT License
Project Creator : azist

private void button6_Click(object sender, EventArgs e)
    {
      var message = string.Empty;
      var value = 1999;
      var timer = new Stopwatch();
      using (var stream = new MemoryStream())
      {
        timer.Start();
        var buffer = new byte[4];
        for (int i=0; i<10000000; i++)
        {
          buffer[0] = (byte)value;
          buffer[1] = (byte)(value >> 8);
          buffer[2] = (byte)(value >> 16);
          buffer[3] = (byte)(value >> 24);
          stream.Write(buffer, 0, 4);
        }
        timer.Stop();
        message += "Writing int as byte array to stream (10000000 iters): " + timer.ElapsedMilliseconds;
      }

      timer.Reset();
      using (var stream = new MemoryStream())
      {
        timer.Start();
        for (int i=0; i<10000000; i++)
        {
          stream.WriteByte((byte)value);
          stream.WriteByte((byte)(value >> 8));
          stream.WriteByte((byte)(value >> 16));
          stream.WriteByte((byte)(value >> 34));
        }
        timer.Stop();
        message +=  Environment.NewLine + "Writing int byte by byte to stream (10000000 iters): " + timer.ElapsedMilliseconds;
      }

      label3.Text = message;
    }

19 View Source File : JSchemaValidatorBuilderTests.cs
License : MIT License
Project Creator : alethic

[TestMethod]
        public void Can_load_really_big_schema()
        {
            var s = JSchema.Parse(File.ReadAllText(Path.Combine(Path.GetDirectoryName(typeof(JSchemaValidatorBuilderTests).replacedembly.Location), "Validation", "ecourt_com_151.json")));
            var o = JObject.Parse(File.ReadAllText(Path.Combine(Path.GetDirectoryName(typeof(JSchemaValidatorBuilderTests).replacedembly.Location), "Validation", "efm.json")));
            var v = JSchemaExpressionBuilder.CreateDefault().Build(s);

            var a = v.Compile();
            a.Invoke(o);
            var sw = new Stopwatch();

            var t = TimeSpan.Zero;
            for (var i = 0; i < 1000; i++)
            {
                sw.Start();
                var r = a.Invoke(o);
                sw.Stop();
                t += sw.Elapsed;
                sw.Reset();
            }
            Console.WriteLine("Average on Fast Validator: " + new TimeSpan((long)(t.Ticks / 1000d)));


            t = TimeSpan.Zero;
            for (var i = 0; i < 1000; i++)
            {
                sw.Start();
                var r = o.IsValid(s);
                sw.Stop();
                t += sw.Elapsed;
                sw.Reset();
            }
            Console.WriteLine("Average on Slow Validator: " + new TimeSpan((long)(t.Ticks / 1000d)));
        }

19 View Source File : CompressAndEncryptBenchmark.cs
License : MIT License
Project Creator : alexis-

public static IEnumerable<CEBenchResult> Run(Stream inStream, int iterationNb)
    {
      List<CEBenchResult> ret = new List<CEBenchResult>();
      Stopwatch sw = new Stopwatch();


      foreach (ArchiveType at in CompressionHelper.AvailableArchives)
      {
        foreach (CompressionType ct in at.GetAvailableCompressions())
        {
          foreach (EncryptionProtocol ep in EncryptionHelper.AvailableProtocols)
          {
            foreach (EncryptionAlgorithm ea in ep.GetAvailableAlgorithms())
            {
              long compSize = 0;

              sw.Reset();
              sw.Start();

              for (int i = 0; i < iterationNb; i++)
              {


                inStream.Seek(0, SeekOrigin.Begin);
                compSize = Process(inStream, at, ct, ep, ea);
              }

              sw.Stop();

              ret.Add(new CEBenchResult()
              {
                ArchiveType = at,
                CompressionType = ct,
                EncryptionProtocol = ep,
                EncryptionAlgorithm = ea,
                TotalRuntime = sw.ElapsedMilliseconds,
                CompressedSize = compSize
              });
            }
          }
        }
      }

      return ret;
    }

19 View Source File : JobAnimationCurveTests.cs
License : MIT License
Project Creator : 5argon

private (long mainTicks, long jobTicks) TestEvaluate(AnimationCurve ac, int iterationCount)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

            var jac = new JobAnimationCurve(ac, Allocator.TempJob);

            NativeArray<float> evaluated = new NativeArray<float>(iterationCount, Allocator.TempJob);
            NativeArray<float> jobEvaluated = new NativeArray<float>(iterationCount, Allocator.TempJob);
            var job = new CurveEvaluationJob
            {
                evaluated = jobEvaluated,
                jobAnimationCurve = jac
            }.Schedule(iterationCount, testEvaluateBatchCount, default(JobHandle));

            sw.Start();
            for (int i = 0; i < evaluated.Length; i++)
            {
                evaluated[i] = ac.Evaluate(i / (float)iterationCount);
            }
            sw.Stop();
            var mainTicks = sw.ElapsedTicks;
            sw.Reset();

            sw.Start();
            job.Complete();
            sw.Stop();
            var jobTicks = sw.ElapsedTicks;

            for (int i = 0; i < evaluated.Length; i++)
            {
                //Within 0.00001f, it is a bit inaccurate.
                replacedert.That(evaluated[i], Is.EqualTo(jobEvaluated[i]).Within(0.0001f),
                $"At index {i} (time {i / (float)iterationCount}) there is a difference of Unity {evaluated[i]} and Job {jobEvaluated[i]} ({evaluated[i] - jobEvaluated[i]})");
            }

            evaluated.Dispose();
            jobEvaluated.Dispose();
            jac.Dispose();

            return (mainTicks, jobTicks);
        }

19 View Source File : GameLoop.cs
License : MIT License
Project Creator : allenwp

public static void Tick()
        {
            swHostTime.Stop();
            PerfTime.RecordPerfTime(swHostTime, ref hostTimePerf);
            swFrameSyncOverhead.Start();

            WriteStateEnum writeState = (WriteStateEnum)WriteState;
            // If we're still waiting for the output to finish reading a buffer, don't do anything else
            if (!firstFrame
                && ((writeState == WriteStateEnum.Buffer1 && FrameOutput.Buffer1 != null)
                    || (writeState == WriteStateEnum.Buffer2 && FrameOutput.Buffer2 != null)))
            {
                // TODO: do something better with thread locks or Parallel library or something that doesn't involve spinning??
                return;
            }

            swFrameSyncOverhead.Stop();
            PerfTime.RecordPerfTime(swFrameSyncOverhead, ref syncOverheadTime);
            var swFrameTime = new Stopwatch();
            swFrameTime.Start();

            // Add first because some components in the Add queue might also be queued for removal.
            // (For example, when adding a component, but then clearing a scene later in the same frame.)
            // But it doesn't make sense that a component would be first removed and then added.
            EnreplacedyAdmin.Instance.AddQueuedComponents();
            EnreplacedyAdmin.Instance.RemoveQueuedComponents();

            // Tick the systems
            if (TickSystems)
            {
                foreach (ECSSystem system in EnreplacedyAdmin.Instance.Systems)
                {
#if !DEBUG
                    try
                    {
#endif
                        system.Tick(EnreplacedyAdmin.Instance);
                        system.Tick();
#if !DEBUG
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
#endif
                 }
            }

            // Finally, prepare and fill the FrameOutput buffer:
            int blankingSampleCount;
            int wastedSampleCount;
            Sample[] finalBuffer = CreateFrameBuffer(EnreplacedyAdmin.Instance.GetComponents<SamplerSingleton>().First().LastSamples, previousFinalSample, out blankingSampleCount, out wastedSampleCount); // FrameOutput.GetCalibrationFrame();
            previousFinalSample = finalBuffer[finalBuffer.Length - 1];

            // Debug test code to simulate tricky double buffer situations
            //if (new Random().Next(60) == 0)
            //{
            //    //Console.WriteLine("Sleeping to simulate a long frame time.");
            //    Thread.Sleep(7);
            //}

            swFrameTime.Stop();
            PerfTime.RecordPerfTime(swFrameTime, ref frameTimePerf);
            swFrameSyncOverhead.Reset();
            swFrameSyncOverhead.Start();

            if (FrameOutput.DebugSaveFrame)
            {
                FrameOutput.DebugSaveBufferToFile(finalBuffer, "Frame Snapshot.csv");
                FrameOutput.DebugSaveFrame = false;
                ASIOOutput.DebugSaveNextFrame = true;
            }

            // "Blit" the buffer and progress the frame buffer write state
            if (writeState == WriteStateEnum.Buffer1)
            {
                FrameOutput.Buffer1 = finalBuffer;
                WriteState = WriteStateEnum.Buffer2;
            }
            else
            {
                FrameOutput.Buffer2 = finalBuffer;
                WriteState = WriteStateEnum.Buffer1;
            }

            // This part regarding the number of starved samples is not thread perfect, but I think it should be
            // correct more than 99.9% of the time...
            int starvedSamples = FrameOutput.StarvedSamples;
            FrameOutput.StarvedSamples = 0;

            // Update GameTime:
            GameTime.LastFrameSampleCount = finalBuffer.Length + starvedSamples;
            if (starvedSamples > 0)
            {
                Console.WriteLine("Added " + starvedSamples + " starved samples to GameTime.LastFrameSampleCount.");
            }

            FrameOutput.FrameCount++;

            if (firstFrame)
            {
                firstFrame = false;
                Console.WriteLine("Finished creating first frame buffer! Starting ASIOOutput now.");
                ASIOOutput.StartDriver();
            }

            if (FrameOutput.FrameCount % 100 == 0)
            {
                int frameRate = (int)Math.Round(1 / ((float)GameTime.LastFrameSampleCount / FrameOutput.SAMPLES_PER_SECOND));
                Console.WriteLine(" " + finalBuffer.Length + " + " + starvedSamples + " starved samples = " + frameRate + " fps (" + blankingSampleCount + " blanking between shapes, " + wastedSampleCount + " wasted) | Frame worst: " + frameTimePerf.worst + " best: " + frameTimePerf.best + " avg: " + frameTimePerf.average + " | Output Sync longest: " + syncOverheadTime.worst + " shortest: " + syncOverheadTime.best + " avg: " + syncOverheadTime.average + " | Host worst: " + hostTimePerf.worst + " best: " + hostTimePerf.best + " avg: " + hostTimePerf.average);
                frameTimePerf = PerfTime.Initial;
                syncOverheadTime = PerfTime.Initial;
                hostTimePerf = PerfTime.Initial;
            }
            swFrameSyncOverhead.Stop();
            swHostTime.Reset();
            swHostTime.Start();
        }

19 View Source File : Pulse.cs
License : MIT License
Project Creator : aimore

public void start()
        {
            IsRun = true;
            stopwatch.Start();
            Device.BeginInvokeOnMainThread(() => {
                Xamarin.Forms.Device.StartTimer(TimeSpan.FromMilliseconds(33), () =>
                {
                    t[0] = (float)(stopwatch.Elapsed.TotalMilliseconds % cycleTime / cycleTime);
                    if (stopwatch.Elapsed.TotalMilliseconds > cycleTime / 3)
                        t[1] = (float)((stopwatch.Elapsed.TotalMilliseconds - cycleTime / 3) % cycleTime / cycleTime);
                    if (stopwatch.Elapsed.TotalMilliseconds > cycleTime * 2 / 3)
                        t[2] = (float)((stopwatch.Elapsed.TotalMilliseconds - cycleTime * 2 / 3) % cycleTime / cycleTime);
                    this.InvalidateSurface();

                    if (!IsRun)
                    {
                        stopwatch.Stop();
                        stopwatch.Reset();
                    }
                    return IsRun;
                });
            });
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : Amine-Smahi

private void video_NewFrame( object sender, NewFrameEventArgs eventArgs )
        {
            if ( this._isRecording )
            {
                this._frameCount++;
                this._writer.WriteVideoFrame( eventArgs.Frame );

                this.lb_1.Invoke( new Action( () =>
                {
                    lb_1.Text = string.Format( @"Frames: {0}", _frameCount );
                } ) );

                this.lb_stopWatch.Invoke( new Action( () =>
                {
                    this.lb_stopWatch.Text = _stopWatch.Elapsed.ToString();
                } ) );
            }
            else
            {
                _stopWatch.Reset();
                Thread.Sleep( 500 );
                _streamVideo.SignalToStop();
                Thread.Sleep( 500 );
                _writer.Close();
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : altimesh

protected override void OnRenderFrame(FrameEventArgs e)
        {
            stopwatch.Start();
            viewAngle += 0.5F;
            lightAngle += 0.5F;
            Init();
            wrapped.Render(surface, Width, Height, iterations, viewDirection, nearFieldLocation, eyeLocation, lightDirection);
            cuda.ERROR_CHECK(cuda.GetLastError(), false);
            cuda.ERROR_CHECK(cuda.DeviceSynchronize(), false);
            GL.ClearColor(Color.Purple);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            GL.UseProgram(shaderProgram);
            GL.ActiveTexture(TextureUnit.Texture0);
            GL.BindTexture(TextureTarget.Texture2D, textureID);

            GL.BindVertexArray(quadVAO);
            GL.DrawArrays(PrimitiveType.TriangleStrip, 0, 4);
            GL.BindVertexArray(0);
            SwapBuffers();
            stopwatch.Stop();
            elapsedMS += stopwatch.ElapsedMilliseconds;
            stopwatch.Reset();
            averageFPS += RenderFrequency;
            frameCounter += 1;
            averageKernelDuration += runner.LastKernelDuration.ElapsedMilliseconds;
            if (elapsedMS > 1000)
            {
                averageFPS /= frameCounter;
                averageKernelDuration /= frameCounter;
                Console.Out.Write("\rKernel time : {0:N2} ms -- FPS : {1:N2}", averageKernelDuration, averageFPS);
                averageFPS = 0.0;
                elapsedMS = 0;
                frameCounter = 0;
                averageKernelDuration = 0;
            }
        }

19 View Source File : TimeCostRecorder.cs
License : MIT License
Project Creator : aillieo

public void Reset()
        {
            stopwatch.Reset();
            testTimes = 0;
            lastStart = 0;
            timeCostMax = 0;
            timeCostMin = long.MaxValue;
        }

19 View Source File : DownloaderObjectModel.cs
License : GNU General Public License v3.0
Project Creator : antikmozib

private async Task<DownloadStatus> ProcessStreamsAsync(long bytesDownloadedPreviously)
        {
            var status = DownloadStatus.Error;
            Task<bool> streamTask;
            HttpRequestMessage request;
            long maxDownloadSpeed = Settings.Default.MaxDownloadSpeed * 1024;
            SemapreplacedSlim semapreplacedProgress = new SemapreplacedSlim(1);
            IProgress<int> streamProgress = new Progress<int>(async (value) =>
            {
                await semapreplacedProgress.WaitAsync();
                this.BytesDownloadedThisSession += value;
                this.TotalBytesCompleted = this.BytesDownloadedThisSession + bytesDownloadedPreviously;
                if (!this.SupportsResume)
                {
                    this.TotalBytesToDownload = this.TotalBytesCompleted;
                }
                _reportBytesProgress.Report(value);
                double progress = (double)this.TotalBytesCompleted / (double)this.TotalBytesToDownload * 100;
                this.Progress = (int)progress;
                semapreplacedProgress.Release();
            });

            // doesn't support multiple streams or each steam under 1 MB
            if (!this.SupportsResume)
            {
                request = new HttpRequestMessage
                {
                    RequestUri = new Uri(this.Url),
                    Method = HttpMethod.Get
                };
            }
            else
            {
                // Set up the request
                request = new HttpRequestMessage
                {
                    RequestUri = new Uri(this.Url),
                    Method = HttpMethod.Get,
                    Headers = { Range = new RangeHeaderValue(bytesDownloadedPreviously, this.TotalBytesToDownload) }
                };
            }

            _ctsPaused = new CancellationTokenSource();
            _ctsCanceled = new CancellationTokenSource();
            _ctPause = _ctsPaused.Token;
            _ctCancel = _ctsCanceled.Token;
            var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(_ctPause, _ctCancel).Token;

            // Process the request
            streamTask = Task.Run(async () =>
            {
                try
                {
                    if (!Directory.Exists(Path.GetDirectoryName(this.Destination)))
                    {
                        throw new AMDownloaderException("Destination directory does not exist.");
                    }
                    if (!File.Exists(TempDestination) && File.Exists(this.Destination))
                    {
                        throw new AMDownloaderException("A new download has not been created.");
                    }

                    using var destinationStream = new FileStream(TempDestination, FileMode.Append, FileAccess.Write);
                    using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
                    using var sourceStream = await response.Content.ReadreplacedtreamAsync();
                    using var binaryWriter = new BinaryWriter(destinationStream);
                    byte[] buffer = new byte[AppConstants.DownloaderStreamBufferLength];
                    int s_bytesReceived = 0;
                    int read;
                    var stopWatch = new Stopwatch();
                    while (true)
                    {
                        linkedToken.ThrowIfCancellationRequested();

                        stopWatch.Start();
                        read = await sourceStream.ReadAsync(buffer, 0, buffer.Length, linkedToken);
                        if (read == 0)
                        {
                            request.Dispose();
                            return true;
                        }
                        else
                        {
                            byte[] data = new byte[read];
                            buffer.ToList().CopyTo(0, data, 0, read);
                            binaryWriter.Write(data, 0, data.Length);
                            s_bytesReceived += read;
                            streamProgress.Report(data.Length);
                        }

                        stopWatch.Stop();

                        // Speed throttler
                        if (maxDownloadSpeed > 0 && stopWatch.ElapsedMilliseconds > 0)
                        {
                            int s_bytesExpected = (int)((double)maxDownloadSpeed / 1000 * stopWatch.ElapsedMilliseconds);
                            if (s_bytesReceived > s_bytesExpected)
                            {
                                long expectedMilliseconds = (long)(1000 / (double)maxDownloadSpeed * s_bytesReceived);
                                long delay = expectedMilliseconds - stopWatch.ElapsedMilliseconds;
                                if (delay > 0) await Task.Delay((int)delay);
                                s_bytesReceived = 0;
                                stopWatch.Reset();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new AMDownloaderException(ex.Message, ex);
                }
            });

            StartReportingProgress();
            StartMeasuringEta();

            try
            {
                // Run the tasks
                var finished = await streamTask;

                // Operation complete; verify state
                // completed successfully
                if (finished)
                {
                    status = DownloadStatus.Finished;
                }
                else
                {
                    status = DownloadStatus.Error;
                }
            }
            catch
            {
                // Paused, cancelled or errored
                if (!linkedToken.IsCancellationRequested)
                {
                    status = DownloadStatus.Error;
                }
                else if (_ctPause.IsCancellationRequested)
                {
                    status = DownloadStatus.Paused;
                }
                else if (_ctCancel.IsCancellationRequested)
                {
                    status = DownloadStatus.Ready;
                }
            }

            // Update final size
            if (!this.SupportsResume) this.TotalBytesToDownload = this.TotalBytesCompleted;

            _ctsPaused = null;
            _ctsCanceled = null;
            _ctPause = default;
            _ctCancel = default;
            _taskCompletion.SetResult(status);
            return status;
        }

19 View Source File : MixedRealityToolkitVisualProfiler.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private void Reset()
        {
            if (defaultMaterial == null)
            {
                defaultMaterial = new Material(Shader.Find("Hidden/Internal-Colored"));
                defaultMaterial.SetFloat("_ZWrite", 1.0f);
                defaultMaterial.SetFloat("_ZTest", (float)UnityEngine.Rendering.CompareFunction.Disabled);
                defaultMaterial.renderQueue = 5000;
            }

            if (defaultInstancedMaterial == null)
            {
                Shader defaultInstancedShader = Shader.Find("Hidden/Instanced-Colored");

                if (defaultInstancedShader != null)
                {
                    defaultInstancedMaterial = new Material(defaultInstancedShader);
                    defaultInstancedMaterial.enableInstancing = true;
                    defaultInstancedMaterial.SetFloat("_ZWrite", 1.0f);
                    defaultInstancedMaterial.SetFloat("_ZTest", (float)UnityEngine.Rendering.CompareFunction.Disabled);
                    defaultInstancedMaterial.renderQueue = 5000;
                }
                else
                {
                    Debug.LogWarning("A shader supporting instancing could not be found for the VisualProfiler, falling back to traditional rendering. This may impact performance.");
                }
            }

            if (Application.isPlaying)
            {
                backgroundMaterial = new Material(defaultMaterial);
                foregroundMaterial = new Material(defaultMaterial);
                defaultMaterial.renderQueue = foregroundMaterial.renderQueue - 1;
                backgroundMaterial.renderQueue = defaultMaterial.renderQueue - 1;

                MeshRenderer meshRenderer = new GameObject().AddComponent<TextMesh>().GetComponent<MeshRenderer>();
                textMaterial = new Material(meshRenderer.sharedMaterial);
                textMaterial.renderQueue = defaultMaterial.renderQueue;
                Destroy(meshRenderer.gameObject);

                MeshFilter quadMeshFilter = GameObject.CreatePrimitive(PrimitiveType.Quad).GetComponent<MeshFilter>();

                if (defaultInstancedMaterial != null)
                {
                    // Create a quad mesh with artificially large bounds to disable culling for instanced rendering.
                    // TODO: Use shared mesh with normal bounds once Unity allows for more control over instance culling.
                    quadMesh = quadMeshFilter.mesh;
                    quadMesh.bounds = new Bounds(Vector3.zero, Vector3.one * float.MaxValue);
                }
                else
                {
                    quadMesh = quadMeshFilter.sharedMesh;
                }

                Destroy(quadMeshFilter.gameObject);
            }

            stopwatch.Reset();
            stopwatch.Start();
        }

19 View Source File : TalkTimerService.cs
License : MIT License
Project Creator : AntonyCorbett

public void Stop()
        {
            _timer.Stop();
            _talkId = null;

            _stopWatch.Reset();
            UpdateTimerValue();
        }

19 View Source File : TestLargeAmount.cs
License : MIT License
Project Creator : aillieo

public void RemoveRandomData()
    {
        if(testData.Count == 0)
        {
            return;
        }
        int index = UnityEngine.Random.Range(0, testData.Count);
        testData.RemoveAt(index);

        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        scrollView.UpdateData(true);
        stopwatch.Stop();
        long time1 = stopwatch.ElapsedMilliseconds;
        stopwatch.Reset();
        stopwatch.Start();
        scrollViewEx.UpdateData(true);
        stopwatch.Stop();
        long time2 = stopwatch.ElapsedMilliseconds;
        UnityEngine.Debug.Log($"cost time in ms:     ScrollView:{time1}     ScrollViewEx:{time2}");
    }

19 View Source File : LoadBalancedActionPool.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

float? ILoadBalanced.ExecuteUpdate(float deltaTime, float nextInterval)
            {
                bool moreWork = true;
                _watch.Reset();
                _watch.Start();
                while (moreWork && _watch.ElapsedMilliseconds < _maxMillisecondsUsedPerFrame)
                {
                    moreWork = _iter.MoveNext();
                }

                this.repeat = moreWork;
                if (!moreWork)
                {
                    LoadBalancedActionPool.Return(this);
                }

                return 0f;
            }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Main(string[] args)
        {

            sedb.StringSet("key1", (string)null);

            var val111 = sedb.StringGet("key1");














            RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,asyncPipeline=true,preheat=100,poolsize=100"));
            cli.Set("TestMGet_null1", "");
            RedisHelper.Set("TestMGet_null1", "");
            sedb.StringSet("TestMGet_string1", String);
            ThreadPool.SetMinThreads(10001, 10001);
            Stopwatch sw = new Stopwatch();
            var tasks = new List<Task>();
            var results = new ConcurrentQueue<string>();

            cli.FlushDb();
            results.Clear();
            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                sedb.StringSet(tmp, String);
                var val = sedb.StringGet(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("StackExchange(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    sedb.StringSet(tmp, String);
                    var val = sedb.StringGet(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchange(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                cli.Set(tmp, String);
                var val = cli.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("FreeRedis(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    cli.Set(tmp, String);
                    var val = cli.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("FreeRedis(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //Task.Run(async () =>
            //{
            //    for (var a = 0; a < 100000; a++)
            //    {
            //        var tmp = Guid.NewGuid().ToString();
            //        await cli.SetAsync(tmp, String);
            //        var val = await cli.GetAsync(tmp);
            //        if (val != String) throw new Exception("not equal");
            //        results.Enqueue(val);
            //    }
            //}).Wait();
            //sw.Stop();
            //Console.WriteLine("FreeRedisAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            //tasks.Clear();
            //results.Clear();
            //cli.FlushDb();

            //FreeRedis.Internal.AsyncRedisSocket.sb.Clear();
            //FreeRedis.Internal.AsyncRedisSocket.sw.Start();
            //sw.Reset();
            //sw.Start();
            //tasks = new List<Task>();
            //for (var a = 0; a < 100000; a++)
            //{
            //    tasks.Add(Task.Run(async () =>
            //    {
            //        var tmp = Guid.NewGuid().ToString();
            //        await cli.SetAsync(tmp, String);
            //        var val = await cli.GetAsync(tmp);
            //        if (val != String) throw new Exception("not equal");
            //        results.Enqueue(val);
            //    }));
            //}
            //Task.WaitAll(tasks.ToArray());
            //sw.Stop();
            ////var sbstr = FreeRedis.Internal.AsyncRedisSocket.sb.ToString()
            ////sbstr = sbstr + sbstr.Split("\r\n").Length + "条消息 ;
            //Console.WriteLine("FreeRedisAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            //tasks.Clear();
            //results.Clear();
            //cli.FlushDb();

            sw.Reset();
            sw.Start();
            using (var pipe = cli.StartPipe())
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    pipe.Set(tmp, String);
                    var val = pipe.Get(tmp);
                }
                var vals = pipe.EndPipe();
                for (var a = 1; a < 200000; a += 2)
                {
                    var val = vals[a].ToString();
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }
            sw.Stop();
            Console.WriteLine("FreeRedisPipeline(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //    cli.Call(new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String));
            //sw.Stop();
            //Console.WriteLine("FreeRedis2: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //{
            //    using (var rds = cli.GetTestRedisSocket())
            //    {
            //        var cmd = new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String);
            //        rds.Write(cmd);
            //        cmd.Read<string>();
            //    }
            //}
            //sw.Stop();
            //Console.WriteLine("FreeRedis4: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                RedisHelper.Set(tmp, String);
                var val = RedisHelper.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("CSRedisCore(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    RedisHelper.Set(tmp, String);
                    var val = RedisHelper.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCore(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    //if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();
        }

19 View Source File : Marshaller.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

internal void ProcessPending()
        {
            if (_queue.count == 0)
            {
                return;
            }

            _watch.Start();

            do
            {
                Action next;
                lock (_queue)
                {
                    next = _queue.Dequeue();
                }

                next();
            }
            while (_queue.count > 0 && _watch.ElapsedMilliseconds < _maxMillisecondsPerFrame);

            _watch.Reset();
        }

19 View Source File : TrafficPolicerHandler.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

private static void SetNextEventStopwatch()
        {
            AmbientEventsPreplaceded++;
            if (AmbientEventsPreplaceded >= NumberOfAmbientEventsBeforeTimer)
            {
                NextEventStopwatch.Reset();
                NextEventStopwatch.Start();
            }
        }

19 View Source File : PathService.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

public IEnumerator ProcessRequests(int maxMillisecondsPerFrame)
        {
            if (this.runAsync)
            {
                throw new InvalidOperationException("Cannot process as coroutine when set to async operation.");
            }

            while (!this.runAsync)
            {
                var next = GetNext();
                if (next == null)
                {
                    if (_stopwatch.IsRunning)
                    {
                        _stopwatch.Reset();
                    }

                    yield return null;
                }
                else
                {
                    var run = true;
                    var subIter = _engine.ProcessRequestCoroutine(next);

                    while (run)
                    {
                        //Start is called multiple places, due to the enumeration going on in various loops. Start is safe to call multiple times, it will simply do nothing if already started.
                        _stopwatch.Start();
                        run = subIter.MoveNext();

                        if (_stopwatch.ElapsedMilliseconds > maxMillisecondsPerFrame)
                        {
                            _stopwatch.Reset();
                            yield return null;
                        }
                    }
                }
            }
        }

19 View Source File : RateMonitor.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void Reset()
        {
            stopwatch.Reset();
        }

19 View Source File : elitePulseIcon.cs
License : MIT License
Project Creator : arqueror

void start()
        {
            IsRun = true;
            stopwatch.Start();
            Xamarin.Forms.Device.StartTimer(TimeSpan.FromMilliseconds(1), () =>
            {
                t[0] = (float)(stopwatch.Elapsed.TotalMilliseconds % cycleTime / cycleTime);
                if (stopwatch.Elapsed.TotalMilliseconds > cycleTime / 3)
                    t[1] = (float)((stopwatch.Elapsed.TotalMilliseconds - cycleTime / 3) % cycleTime / cycleTime);
                if (stopwatch.Elapsed.TotalMilliseconds > cycleTime * 2 / 3)
                    t[2] = (float)((stopwatch.Elapsed.TotalMilliseconds - cycleTime * 2 / 3) % cycleTime / cycleTime);
                this.InvalidateSurface();

                if (!IsRun)
                {
                    stopwatch.Stop();
                    stopwatch.Reset();
                }
                return IsRun;
            });
        }

19 View Source File : PerformanceTestsRunner.cs
License : MIT License
Project Creator : alelievr

static PerformanceResult RunTestForGraph(WorldGraph graph)
		{
			var result = new PerformanceResult();
			Stopwatch sw = new Stopwatch();

			result.name = graph.name;

			sw.Start();
			graph.ProcessOnce();
			sw.Stop();
			result.processOnceTime = sw.Elapsed.TotalMilliseconds;

			sw.Reset();
			sw.Start();

			graph.Process();

			sw.Stop();
			result.processTime = sw.Elapsed.TotalMilliseconds;

			result.nodeProcessTime = new NodeProcessTime[graph.allNodes.Count()];
			for (int i = 0; i < result.nodeProcessTime.Length; i++)
			{
				var node = graph.allNodes.ElementAt(i);
				result.nodeProcessTime[i] = new NodeProcessTime(node.name, node.processTime);
			}
			
			result.totalAllocatedMemory = Profiler.GetTotalAllocatedMemoryLong();
			result.totalReservedMemory = Profiler.GetTotalReservedMemoryLong();
			result.totalUnusedReservedMemory = Profiler.GetTotalUnusedReservedMemoryLong();

			return result;
		}

19 View Source File : Transition.cs
License : MIT License
Project Creator : awaescher

public void Run()
		{
			// We find the current start values for the properties we 
			// are animating...
			foreach (TransitionedPropertyInfo info in TransitionedProperties)
			{
				object value = info.PropertyInfo.GetValue(info.Target, null);
				info.StartValue = info.ManagedType.Copy(value);
			}

			// We start the stopwatch. We use this when the timer ticks to measure 
			// how long the transition has been runnning for...
			_stopwatch.Reset();
			_stopwatch.Start();

			// We register this transition with the transition manager...
			TransitionManager.GetInstance().Register(this);
		}

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Main(string[] args)
        {
            RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,asyncPipeline=true,preheat=100,poolsize=100"));
            cli.Set("TestMGet_null1", "");
            RedisHelper.Set("TestMGet_null1", "");
            sedb.StringSet("TestMGet_string1", String);
            ThreadPool.SetMinThreads(10001, 10001);
            Stopwatch sw = new Stopwatch();
            var tasks = new List<Task>();
            var results = new ConcurrentQueue<string>();

            cli.FlushDb();
            while (results.TryDequeue(out var del)) ;
            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                sedb.StringSet(tmp, String);
                var val = sedb.StringGet(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("StackExchange(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    sedb.StringSet(tmp, String);
                    var val = sedb.StringGet(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchange(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                cli.Set(tmp, String);
                var val = cli.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("FreeRedis(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    cli.Set(tmp, String);
                    var val = cli.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("FreeRedis(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await cli.SetAsync(tmp, String);
                    var val = await cli.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("FreeRedisAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            //FreeRedis.Internal.AsyncRedisSocket.sb.Clear();
            //FreeRedis.Internal.AsyncRedisSocket.sw.Start();
            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await cli.SetAsync(tmp, String);
                    var val = await cli.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            //var sbstr = FreeRedis.Internal.AsyncRedisSocket.sb.ToString()
            //sbstr = sbstr + sbstr.Split("\r\n").Length + "条消息 ;
            Console.WriteLine("FreeRedisAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            using (var pipe = cli.StartPipe())
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    pipe.Set(tmp, String);
                    var val = pipe.Get(tmp);
                }
                var vals = pipe.EndPipe();
                for (var a = 1; a < 200000; a += 2)
                {
                    var val = vals[a].ToString();
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }
            sw.Stop();
            Console.WriteLine("FreeRedisPipeline(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //    cli.Call(new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String));
            //sw.Stop();
            //Console.WriteLine("FreeRedis2: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //{
            //    using (var rds = cli.GetTestRedisSocket())
            //    {
            //        var cmd = new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String);
            //        rds.Write(cmd);
            //        cmd.Read<string>();
            //    }
            //}
            //sw.Stop();
            //Console.WriteLine("FreeRedis4: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                RedisHelper.Set(tmp, String);
                var val = RedisHelper.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("CSRedisCore(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    RedisHelper.Set(tmp, String);
                    var val = RedisHelper.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCore(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    //if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();
        }

19 View Source File : PerformanceAspect.cs
License : MIT License
Project Creator : aykutsahin98

protected override void OnAfter(IInvocation invocation)
        {
            if (_stopwatch.Elapsed.TotalSeconds > _interval)
            {
                Debug.WriteLine($"Performance : {invocation.Method.DeclaringType.FullName}.{invocation.Method.Name}-->{_stopwatch.Elapsed.TotalSeconds}");
            }
            _stopwatch.Reset();
        }

19 View Source File : MapVisualizerPerformance.cs
License : MIT License
Project Creator : alen-smajic

protected virtual void Awake()
		{
			TotalTime = 0;
			_currentTest = 1;
			_map = FindObjectOfType<AbstractMap>();
			_mapVisualizer = _map.MapVisualizer;

			_mapVisualizer.OnMapVisualizerStateChanged += (s) =>
			{
				if (s == ModuleState.Working)
				{
					_sw.Reset();
					_sw.Start();
				}
				else if (s == ModuleState.Finished)
				{
					_sw.Stop();
					if (_currentTest > 1)
					{
						TotalTime += _sw.ElapsedMilliseconds;
						UnityEngine.Debug.Log("Test " + _currentTest + ": " + _sw.ElapsedMilliseconds);
					}
					else
					{
						_firstRun = _sw.ElapsedMilliseconds;
					}

					if (TestCount > _currentTest)
					{
						_currentTest++;
						Invoke("Run", 1f);
					}
					else
					{
						if (_currentTest > 1)
						{
							UnityEngine.Debug.Log("First Run:        " + _firstRun + " \r\nRest Average: " + TotalTime / (_currentTest - 1));
						}
					}
				}
			};
		}

19 View Source File : PerformanceAspect.cs
License : MIT License
Project Creator : ahmet-cetinkaya

protected override void OnAfter(IInvocation invocation)
        {
            if (_stopwatch.Elapsed.TotalSeconds > _interval)
                Debug.WriteLine(
                    $"Performance : {invocation.Method.DeclaringType.FullName}.{invocation.Method.Name}-->{_stopwatch.Elapsed.TotalSeconds}");
            _stopwatch.Reset();
        }

19 View Source File : Client.cs
License : MIT License
Project Creator : 1ZouLTReX1

public static void ResetStopWatch()
    {
        stopWatch.Reset();
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Main(string[] args)
        {

            var info = cli.Info();
            var info1 = cli.Info("server");

            RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,database=2"));
            cli.Set("TestMGet_null1", String);
            RedisHelper.Set("TestMGet_null1", String);
            sedb.StringSet("TestMGet_string1", String);

            Stopwatch sw = new Stopwatch();
            sw.Start();
            cli.Set("TestMGet_string1", String);
            cli.Set("TestMGet_bytes1", Bytes);
            cli.Set("TestMGet_string2", String);
            cli.Set("TestMGet_bytes2", Bytes);
            cli.Set("TestMGet_string3", String);
            cli.Set("TestMGet_bytes3", Bytes);
            sw.Stop();
            Console.WriteLine("FreeRedis: " + sw.ElapsedMilliseconds + "ms");

            sw.Reset();
            sw.Start();
            cli.Set("TestMGet_string1", String);
            cli.Set("TestMGet_bytes1", Bytes);
            cli.Set("TestMGet_string2", String);
            cli.Set("TestMGet_bytes2", Bytes);
            cli.Set("TestMGet_string3", String);
            cli.Set("TestMGet_bytes3", Bytes);
            sw.Stop();
            Console.WriteLine("FreeRedis: " + sw.ElapsedMilliseconds + "ms");

            sw.Reset();
            sw.Start();
            RedisHelper.Set("TestMGet_string1", String);
            RedisHelper.Set("TestMGet_bytes1", Bytes);
            RedisHelper.Set("TestMGet_string2", String);
            RedisHelper.Set("TestMGet_bytes2", Bytes);
            RedisHelper.Set("TestMGet_string3", String);
            RedisHelper.Set("TestMGet_bytes3", Bytes);
            sw.Stop();
            Console.WriteLine("CSRedisCore: " + sw.ElapsedMilliseconds + "ms");

            sw.Reset();
            sw.Start();
            sedb.StringSet("TestMGet_string1", String);
            sedb.StringSet("TestMGet_bytes1", Bytes);
            sedb.StringSet("TestMGet_string2", String);
            sedb.StringSet("TestMGet_bytes2", Bytes);
            sedb.StringSet("TestMGet_string3", String);
            sedb.StringSet("TestMGet_bytes3", Bytes);
            sw.Stop();
            Console.WriteLine("StackExchange: " + sw.ElapsedMilliseconds + "ms");

        }

19 View Source File : UMAGeneratorBuiltin.cs
License : Apache License 2.0
Project Creator : A7ocin

public override void Work()
		{
			if (!IsIdle())
			{
				stopWatch.Reset();
				stopWatch.Start();
				OnDirtyUpdate();
				ElapsedTicks += stopWatch.ElapsedTicks;
#if UNITY_EDITOR
				UnityEditor.EditorUtility.SetDirty(this);
#endif
				stopWatch.Stop();
				UMATime.ReportTimeSpendtThisFrameTicks(stopWatch.ElapsedTicks);
			}
		}

19 View Source File : TestLargeAmount.cs
License : MIT License
Project Creator : aillieo

public void ScrollToRandom()
    {
        int index = UnityEngine.Random.Range(0, testData.Count);

        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        scrollView.ScrollTo(index);
        stopwatch.Stop();
        long time1 = stopwatch.ElapsedMilliseconds;
        stopwatch.Reset();
        stopwatch.Start();
        scrollViewEx.ScrollTo(index);
        stopwatch.Stop();
        long time2 = stopwatch.ElapsedMilliseconds;
        UnityEngine.Debug.Log($"cost time in ms:     ScrollView:{time1}     ScrollViewEx:{time2}");
    }

19 View Source File : MonKeyForm.cs
License : MIT License
Project Creator : altugbakan

private async void FindSpecificMonKeyButton_Click(object sender, EventArgs e)
        {
            if (findSpecificMonKeyButton.Text == "Find Specific MonKey")
            {
                stopwatch.Start();
                cancellationTokenSource = new CancellationTokenSource();
                while (Properties.Settings.Default.SavedAccessories == null)
                {
                    DialogResult dialogResult = MessageBox.Show("Seems like you haven't yet created a" +
                        " specific MonKey. Want to create one?", "Warning", MessageBoxButtons.YesNo);
                    if (dialogResult == DialogResult.Yes)
                    {
                        SimpleSettings settingsForm = new SimpleSettings();
                        settingsForm.ShowDialog();
                    }
                    else
                    {
                        GetRandomMonKeyButton_Click(null, null);
                        return;
                    }
                }
                findSpecificMonKeyButton.Text = "Cancel";
                Result result = await Task.Run(
                    () => SearchMonKeys(
                        cancellationTokenSource.Token,
                        Properties.Settings.Default.SavedAccessories.Cast<string>().ToList(),
                        Properties.Settings.Default.MonKeyRequestAmount,
                        delegate (Progress progress) { ReportProgress(progress); }
                    )
                );

                if (cancellationTokenSource.IsCancellationRequested)
                {
                    searchedLabel.Text = "";
                }
                else if (result == null)
                {
                    MessageBox.Show("No internet connection.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    Drawing.DrawSvg(await result.MonKey.GetMonKeySvg(monKeyPictureBox.Width), monKeyPictureBox);
                    addressTextBox.Text = result.MonKey.Address;
                    seedTextBox.Text = result.MonKey.Seed;
                    searchedLabel.Text = $"Found MonKey after {result.Iterations:#,#} MonKeys.";
                }

                findSpecificMonKeyButton.Text = "Find Specific MonKey";
            }
            else
            {
                stopwatch.Stop();
                stopwatch.Reset();
                cancellationTokenSource.Cancel();
            }
        }

See More Examples