private static MicroStopwatch GetStopwatch() { var stopwatch = new MicroStopwatch(); stopwatch.Start(); return(stopwatch); }
private void TimerThread() { long nextNotification = 0; var microStopwatch = new MicroStopwatch(); microStopwatch.Start(); while (!_stopTimer) { nextNotification += _timerIntervalInMicroSec; long elapsedMicroseconds; while ((elapsedMicroseconds = microStopwatch.ElapsedMicroseconds) < nextNotification) { Thread.SpinWait(10); } var timerLateBy = elapsedMicroseconds - nextNotification; _handler(elapsedMicroseconds, timerLateBy); } microStopwatch.Stop(); }
private void EmulatorWork() { double cpuSecondsElapsed = 0.0f; MicroStopwatch s = new MicroStopwatch(); s.Start(); while (emulate) { uint cycles = emulator.DecodeAndDispatch(); // timer handling // note: there's nothing quite reliable / precise enough in cross-platform .Net // so this is quite hack-ish / dirty cpuSecondsElapsed += cycles / GBZ80.ClockSpeed; double realSecondsElapsed = s.ElapsedMicroseconds * 1000000; if (realSecondsElapsed - cpuSecondsElapsed > 0.0) // dirty wait { realSecondsElapsed = s.ElapsedMicroseconds * 1000000; } if (s.ElapsedMicroseconds > 1000000) // dirty restart every seconds to not loose too many precision { // TODO //s.Restart(); cpuSecondsElapsed -= 1.0; } } }
protected TimedExecutable(string name, int timeoutMillis) { Name = name; TimeoutMilliseconds = timeoutMillis; ExpiresSilently = false; WaitWatcher = new MicroStopwatch(); LogType = LogType; LogMessageType = LogMessageType.Trace; }
public TrayMover(string srcName, string dstName) { Name = "TrayMover(" + srcName + "->" + dstName + ")"; IsSynchronous = false; LockResources = true; SourceLockOwner = this; CompletionCause = CompletionCause.Pending; WaitWatcher = new MicroStopwatch(); _dispatcher = new SimpleDispatcher(Name); }
protected virtual void NotificationTimer(ref long timerIntervalInMicroSec, ref long ignoreEventIfLateBy, ref bool stopTimer) { int timerCount = 0; long nextNotification = 0; MicroStopwatch microStopwatch = new MicroStopwatch(); microStopwatch.Start(); while (!stopTimer) { long callbackFunctionExecutionTime = microStopwatch.ElapsedMicroseconds - nextNotification; long timerIntervalInMicroSecCurrent = System.Threading.Interlocked.Read(ref timerIntervalInMicroSec); long ignoreEventIfLateByCurrent = System.Threading.Interlocked.Read(ref ignoreEventIfLateBy); nextNotification += timerIntervalInMicroSecCurrent; timerCount++; long elapsedMicroseconds = 0; while ((elapsedMicroseconds = microStopwatch.ElapsedMicroseconds) < nextNotification) { System.Threading.Thread.SpinWait(10); } long timerLateBy = elapsedMicroseconds - nextNotification; if (timerLateBy >= ignoreEventIfLateByCurrent) { continue; } MicroTimerEventArgs microTimerEventArgs = new MicroTimerEventArgs(timerCount, elapsedMicroseconds, timerLateBy, callbackFunctionExecutionTime); MicroTimerElapsed(this, microTimerEventArgs); } microStopwatch.Stop(); }
private static string GetElapsedTime(MicroStopwatch stopwatch) { return($"Elapsed: {stopwatch.ElapsedMilliseconds.ToString("0ms").PadRight(6)}({stopwatch.ElapsedMicroseconds}us)"); }
private List <TradeSignal> Evaluate(Dictionary <Selection, IEnumerable <Bar> > marketData, IEnumerable <object> parameterItem, Selection triggerInstrument = null, IEnumerable <Tick> ticks = null) { /* Evaluate supplied data bars using provided parameters * and return a collection of trades on successful evaluation * Hint: you can pass these bars to your IndicatorBase instance in its Calculate() method * and you can use current parameter values as that IndicatorBase parameters */ var dataTickframes = marketData.Keys.Where(p => p.Timeframe == Timeframe.Tick); Dictionary <Selection, IEnumerable <Bar> > trigInstrData = new Dictionary <Selection, IEnumerable <Bar> >(); #region Internal Backtest if (_execTradesParam.EvalCount % 10 == 0 && _internalBacktest == true) { _internalBacktest = false; var backtestSet = new BacktestSettings { InitialBalance = 10000, TransactionCosts = 0, Risk = 0, BarsBack = 5, }; Alert("----------------------------------"); Alert("START Internal Backtest"); Alert("----------------------------------"); var res = Backtest(false); var tradeCount = res?[0].Summaries?.Select(i => i.NumberOfTradeSignals).DefaultIfEmpty(0)?.Sum() ?? 0; _internalBacktest = true; Alert("Evaluate(): Internal Backtest Trades: " + tradeCount); Alert("----------------------------------"); Alert("STOP Internal Backtest"); Alert("----------------------------------"); } #endregion #region Prepare marketdata and pass it to trading logic for processing if (StartMethod == StartMethod.NewBar && triggerInstrument != null) { trigInstrData.Clear(); trigInstrData.Add(triggerInstrument, DataProvider.GetBars(triggerInstrument)); } if (State == SignalState.Backtesting) // && dataTickframes.Count() > 0) { var timer = new MicroStopwatch(); timer.Start(); var trades = new List <TradeSignal>(); trades = BacktestPriceSegmentation.BacktestPriceSegmentProcessor(this, marketData, _execTradesParam, backtestPriceConst, Calculate, trigInstrData, ticks); timer.Stop(); Alert($"Init instrumentData: ExecutionTime = {timer.ElapsedMicroseconds:#,0} µs"); return(trades); } try { return(Calculate(marketData)); } catch (Exception e) { Alert($"Evaluate(): Failed to Run on Usercode: {e.Message}"); return(new List <TradeSignal>()); } #endregion }
public MicroTimerStrategy() { mTimer = new MicroStopwatch(); }
public void BackgroundUpdate(object sender, DoWorkEventArgs e) { Log.Out("[WalkerSim] Worker Start"); MicroStopwatch updateWatch = new MicroStopwatch(); updateWatch.Start(); MicroStopwatch frameWatch = new MicroStopwatch(); double totalElapsed = 0.0; double dtAverage = 0.0; double nextReport = 10.0; float updateRate = 1.0f / (float)_config.UpdateInterval; BackgroundWorker worker = sender as BackgroundWorker; while (worker.CancellationPending == false) { bool isPaused = !(_playerZones.HasPlayers() || !_config.PauseWithoutPlayers); double dt = updateWatch.ElapsedMicroseconds / 1000000.0; updateWatch.ResetAndRestart(); totalElapsed += dt; if (!isPaused) { dtAverage += dt; dtAverage *= 0.5; double dtScaled = dt; dtScaled *= _timeScale; _accumulator += dtScaled; } else { dtAverage = 0.0; } _server.Update(); if (_accumulator < updateRate) { if (isPaused) { System.Threading.Thread.Sleep(1000); } else { System.Threading.Thread.Sleep(1); } } else { frameWatch.ResetAndRestart(); try { while (_accumulator >= updateRate) { var world = GameManager.Instance.World; if (world == null) { // Work-around for client only support, some events are skipped like for when the player exits. Log.Out("[WalkerSim] World no longer exists, stopping simulation"); _worker.CancelAsync(); break; } _accumulator -= updateRate; // Prevent long updates in case the timescale is cranked up. if (frameWatch.ElapsedMilliseconds >= 66) { break; } UpdateInactiveZombies(updateRate); } } catch (Exception ex) { //Log.Out("Exception in worker: {0}", ex.Message); Log.Error("[WalkerSim] Exception in worker"); Log.Exception(ex); } } BroadcastMapData(); if (totalElapsed >= nextReport && !isPaused) { double avgFps = 1 / dtAverage; if (avgFps < (1.0f / updateRate)) { Log.Warning("[WalkerSim] Detected bad performance, FPS Average: {0}", avgFps); } nextReport = totalElapsed + 60.0; } } Log.Out("[WalkerSim] Worker Finished"); _running = false; }
public void ProcessSpawnQueue() { // 10,000,000 ticks per second if (DateTime.UtcNow.Ticks <= _lastTick + 500000L) { return; } _lastTick = DateTime.UtcNow.Ticks; if (SpawnQueue.Count == 0) { return; } lock (SpawnQueue) { var sw = new MicroStopwatch(); for (; SpawnQueue.Count > 0 && sw.ElapsedTicks < 250000L;) { //todo: max execution time limit so that too many queued spawns doesnt bog server try { //if obey maxspawns use below //if (GameStats.GetInt(EnumGameStats.EnemyCount) >= GamePrefs.GetInt(EnumGamePrefs.MaxSpawnedZombies)) return; var spawn = SpawnQueue.Dequeue(); var world = GameManager.Instance.World; if (world.GetRandomSpawnPositionMinMaxToPosition(new Vector3(spawn.SpawnPos.x, spawn.SpawnPos.y, spawn.SpawnPos.z), spawn.MinRange, spawn.MaxRange, false, out var pos, true)) { //todo: change to use EntityCreationData method? var entity = EntityFactory.CreateEntity(spawn.EntityClassId, pos) as EntityEnemy; if (entity == null) { continue; } //_entity.lifetime //todo: log entityid for checking against spawn counts in wave etc //string name = ""; //if (EntityClass.list.ContainsKey(_entity.entityClass)) //{ // name = EntityClass.list[_entity.entityClass].entityClassName; //} lock (HordeSpawners) { //todo: increase counters and disable spawner if limits reached, alter settings if next wave etc spawn.EntityId = entity.entityId; if (HordeSpawners.ContainsKey(spawn.SpawnerId.ToString())) { HordeSpawners[spawn.SpawnerId.ToString()] .Spawns.Add(entity.entityId.ToString(), spawn); } else { HordeSpawners.Add(spawn.SpawnerId.ToString(), new HordeSpawner { Spawns = new Dictionary <string, Spawn> { { entity.entityId.ToString(), spawn } } }); } } entity.bIsChunkObserver = spawn.IsObserver; //will make them move at night speed entity.isFeral = spawn.IsFeral; entity.speedApproach = entity.speedApproach * spawn.SpeedMul; if (spawn.SpeedBase > 0f) { entity.speedApproach = spawn.SpeedBase * spawn.SpeedMul; } if (spawn.NightRun) { entity.speedApproachNight = entity.speedApproachNight * spawn.SpeedMul; } else { entity.speedApproachNight = entity.speedApproach; } Log.Out($"{Config.ModPrefix} Spawning {entity.entityType}({entity.entityId}):{entity.EntityName} @{pos.x} {pos.y} {pos.z} => {spawn.TargetPos.x} {spawn.TargetPos.y} {spawn.TargetPos.z}"); world.Entities.Add(entity.entityId, entity); if (entity.IsEntityAttachedToChunk && !entity.addedToChunk) { //todo: need to generate chunk and delay spawn if chunk isnt loaded? var chunk = world.GetChunkFromWorldPos(entity.GetBlockPosition()) as Chunk; chunk?.AddEntityToChunk(entity); } world.audioManager?.EntityAddedToWorld(entity, world); world.entityDistributer.Add(entity); entity.Spawned = true; world.aiDirector.AddEntity(entity); entity.SetInvestigatePosition(new Vector3(spawn.TargetPos.x, spawn.TargetPos.y, spawn.TargetPos.z), 6000); } else { Log.Out( $"{Config.ModPrefix} Unable to find Spawn Point near {spawn.TargetPos}, min:{spawn.MinRange}, max:{spawn.MaxRange}"); } }
public void BackgroundUpdate(object sender, DoWorkEventArgs e) { Logger.Info("Worker Start"); MicroStopwatch updateWatch = new MicroStopwatch(); updateWatch.Start(); MicroStopwatch frameWatch = new MicroStopwatch(); double totalElapsed = 0.0; double dtAverage = 0.0; double nextReport = 10.0; float updateRate = 1.0f / (float)Config.Instance.UpdateInterval; var worker = (BackgroundWorker)sender; while (worker.CancellationPending == false) { #if DEBUG bool isPaused = false; #else bool isPaused = !(_playerZones.HasPlayers() || !Config.Instance.PauseWithoutPlayers); #endif if (Config.Instance.PauseDuringBloodmon && _state.IsBloodMoon) { isPaused = true; } double dt = updateWatch.ElapsedMicroseconds / 1000000.0; updateWatch.ResetAndRestart(); totalElapsed += dt; if (!isPaused) { dtAverage += dt; dtAverage *= 0.5; double dtScaled = dt; dtScaled *= _state.Timescale; _accumulator += dtScaled; } else { dtAverage = 0.0; lock (_worldEvents) { // Don't accumulate world events while paused. _worldEvents.Clear(); } } _server.Update(); if (_accumulator < updateRate) { System.Threading.Thread.Sleep(isPaused ? 100 : 1); } else { frameWatch.ResetAndRestart(); try { while (_accumulator >= updateRate) { var world = GameManager.Instance.World; if (world == null) { // Work-around for client only support, some events are skipped like for when the player exits. Logger.Info("World no longer exists, stopping simulation"); _worker.CancelAsync(); break; } _accumulator -= updateRate; // Prevent long updates in case the timescale is cranked up. if (frameWatch.ElapsedMilliseconds >= 66) { break; } UpdateInactiveZombies(updateRate); } } catch (Exception ex) { Logger.Error("Exception in worker"); Log.Exception(ex); } } lock (_server) { SendPlayerZones(_server, null); SendInactiveZombieList(_server, null); SendActiveZombieList(_server, null); } if (totalElapsed >= nextReport && !isPaused) { double avgFps = 1 / dtAverage; if (avgFps < (1.0f / updateRate)) { Logger.Warning("Detected bad performance, FPS Average: {0}", avgFps); } nextReport = totalElapsed + 60.0; } } Logger.Info("Worker Finished"); _running = false; }
void NotificationTimer(ref long timerIntervalInMicroSec, ref long ignoreEventIfLateBy, ref bool stopTimer) { var timerCount = 0; long nextNotification = 0; var microStopwatch = new MicroStopwatch(); microStopwatch.Start(); while (!stopTimer) { var callbackFunctionExecutionTime = microStopwatch.ElapsedMicroseconds - nextNotification; var timerIntervalInMicroSecCurrent = Interlocked.Read(ref timerIntervalInMicroSec); var ignoreEventIfLateByCurrent = Interlocked.Read(ref ignoreEventIfLateBy); nextNotification += timerIntervalInMicroSecCurrent; timerCount++; long elapsedMicroseconds; while ((elapsedMicroseconds = microStopwatch.ElapsedMicroseconds) < nextNotification) { Thread.SpinWait(10); } var timerLateBy = elapsedMicroseconds - nextNotification; if (timerLateBy >= ignoreEventIfLateByCurrent) { continue; } MicroTimerEventArgs microTimerEventArgs = new MicroTimerEventArgs(timerCount, elapsedMicroseconds, timerLateBy, callbackFunctionExecutionTime); MicroTimerElapsed?.Invoke(this, microTimerEventArgs); } microStopwatch.Stop(); }