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; } } }
private void EnsureWatchStarted() { if (mTimer.IsRunning) { return; } lastWaitEnded = 0; mTimer.Start(); }
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(); }
static MicroTimer MicroTimer100; // timer 100hz public static void StartTimerServices() { MicroStopwatch.Start(); MicroTimer50 = new MicroTimer(); MicroTimer50.Interval = 20000; // In nanoseconds MicroTimer50.MicroTimerElapsed += handleTimer50; // Can choose to ignore event if late by Xµs (by default will try to catch up) // microTimer.IgnoreEventIfLateBy = 500; // 500µs (0.5ms) MicroTimer50.Enabled = true; // Start timer MicroTimer100 = new MicroTimer(); MicroTimer100.Interval = 10000; // In nanoseconds MicroTimer100.MicroTimerElapsed += handleTimer100; // Can choose to ignore event if late by Xµs (by default will try to catch up) // microTimer.IgnoreEventIfLateBy = 500; // 500µs (0.5ms) MicroTimer100.Enabled = true; // Start timer }
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 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 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(); }