Record the event elapsed time to the histogram and delay initiation of the next event based
on the load distribution.
540855
void delay(long alreadyElapsed) {
    recorder.recordValue(alreadyElapsed);
    if (distribution != null) {
      long nextPermitted = Math.round(distribution.sample() * 1000000000.0);
      if (nextPermitted > alreadyElapsed) {
        LockSupport.parkNanos(nextPermitted - alreadyElapsed);
      }
    }
  }
36601
function() {
      this.forEachLine(function(text, eventBase, cpuNumber, pid, ts) {
        var eventName = eventBase.eventName;
        if (eventName !== 'tracing_mark_write' && eventName !== '0')
          return;
        if (traceEventClockSyncRE.exec(eventBase.details))
          this.traceClockSyncEvent(eventName, cpuNumber, pid, ts, eventBase);
        if (realTimeClockSyncRE.exec(eventBase.details)) {
          // This entry maps realtime to clock_monotonic; store in the model
          // so that importers parsing files with realtime timestamps can
          // map this back to monotonic.
          var match = realTimeClockSyncRE.exec(eventBase.details);
          this.model_.realtime_to_monotonic_offset_ms = ts - match[1];
        }
        if (genericClockSyncRE.exec(eventBase.details))
          this.traceClockSyncEvent(eventName, cpuNumber, pid, ts, eventBase);
      }.bind(this));
    }
99310
def call_later(self, delay, func, *args, **kwargs):
        
        # "quantize" the delay to the nearest bucket
        now = self._get_seconds()
        real_time = int(now + delay) * 1000
        real_time -= int(real_time % self._bucket_milliseconds)
        call = _BatchedCall(self, real_time, lambda: func(*args, **kwargs))
        try:
            self._buckets[real_time][1].append(call)
        except KeyError:
            # new bucket; need to add "actual" underlying IDelayedCall
            diff = (real_time / 1000.0) - now
            # we need to clamp this because if we quantized to the
            # nearest second, but that second is actually (slightly)
            # less than the current time 'diff' will be negative.
            delayed_call = self._create_delayed_call(
                max(0.0, diff),
                self._notify_bucket, real_time,
            )
            self._buckets[real_time] = (delayed_call, [call])
        return call
966828
def timing(self, stat, time, sample_rate=1):
        
        stats = {stat: "%f|ms" % time}
        self.send(stats, sample_rate)
1153656
def ProcessTask(self, target, args, name, queueing_time):
    """"""

    if self.pool.name:
      time_in_queue = time.time() - queueing_time
      stats_collector_instance.Get().RecordEvent(
          _QUEUEING_TIME_METRIC, time_in_queue, fields=[self.pool.name])

      start_time = time.time()
    try:
      target(*args)
    # We can't let a worker die because one of the tasks it has to process
    # throws an exception. Therefore, we catch every error that is
    # raised in the call to target().
    except Exception as e:  # pylint: disable=broad-except
      if self.pool.name:
        stats_collector_instance.Get().IncrementCounter(
            _TASK_EXCEPTIONS_METRIC, fields=[self.pool.name])
      logging.exception("Caught exception in worker thread (%s): %s", name,
                        str(e))

    if self.pool.name:
      total_time = time.time() - start_time
      stats_collector_instance.Get().RecordEvent(
          _WORKING_TIME_METRIC, total_time, fields=[self.pool.name])
1321725
void transformAndQueue(T event, long systemCurrentTimeMillis) {
        // if you're super unlucky, this blows up the stack
        if (rand.nextDouble() < 0.05) {
            // duplicate this message (note recursion means maybe more than duped)
            transformAndQueue(event, systemCurrentTimeMillis);
        }

        long delayms = nextZipfDelay();
        delayed.add(systemCurrentTimeMillis + delayms, event);
    }
545347
private void waitForNextRecord(long startingTime, long timestamp) {
        if(mFirstTimestamp == 0) {
            mFirstTimestamp = timestamp;
            Log.d(TAG, "Storing " + timestamp + " as the first " +
                    "timestamp of the trace file");
        }
        long targetTime = startingTime + (timestamp - mFirstTimestamp);
        long sleepDuration = Math.max(targetTime - System.currentTimeMillis(), 0);
        try {
            Thread.sleep(sleepDuration);
        } catch(InterruptedException e) {}
    }
934600
public synchronized void setFlushInterval(long delay, long seconds) {
        if (m_flush != null) {
            m_flush.cancel(false);
            m_flush = null;
        }
        if (seconds > 0) {
            m_flush = m_ses.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    try {
                        flush();
                    } catch (Exception e) {
                        loaderLog.error("Failed to flush loader buffer, some tuples may not be inserted.", e);
                    }
                }
            }, delay, seconds, TimeUnit.SECONDS);
        }
    }
1278891
private void startPerformanceSnapshot() {
        // Create new snapshot
        mPerfSnapshot = new Bundle();

        // Add initial binder counts
        Bundle binderCounts = getBinderCounts();
        for (String key : binderCounts.keySet()) {
            mPerfSnapshot.putLong("pre_" + key, binderCounts.getLong(key));
        }

        // Force a GC and zero out the performance counters. Do this
        // before reading initial CPU/wall-clock times so we don't include
        // the cost of this setup in our final metrics.
        startAllocCounting();

        // Record CPU time up to this point, and start timing. Note: this
        // must happen at the end of this method, otherwise the timing will
        // include noise.
        mSnapshotExecTime = SystemClock.uptimeMillis();
        mSnapshotCpuTime = Process.getElapsedCpuTime();
    }
1136562
@Tick(delay = 200L, unit = TimeUnit.MILLISECONDS)
  protected void processGDATRecords() throws InvocationTargetException, IllegalAccessException {
    stopwatch.reset();
    stopwatch.start();
    while (!recordQueue.isEmpty()) {
      // Time since start of processing in Seconds
      long elapsedTime = stopwatch.elapsedTime(TimeUnit.SECONDS);
      if (elapsedTime >= Constants.TICKER_TIMEOUT) {
        break;
      }
      Map.Entry<String, GDATDecoder> record = recordQueue.getNext();
      methodsDriver.invokeMethods(record.getKey(), record.getValue());
    }
    stopwatch.stop();
  }
1215026
def progress_callback(self, action, node, elapsed_time=None):
        
        if action == 'load_start':
            self.stdout.write('Loading fixture {}.{}...'.format(*node),
                              ending='')
            self.stdout.flush()
        elif action == 'load_success':
            message = 'SUCCESS'
            if elapsed_time:
                message += ' ({:.03} seconds) '.format(elapsed_time)

            self.stdout.write(message)
171490
def set_event(self,
                  simulation_start=None,
                  simulation_duration=None,
                  simulation_end=None,
                  rain_intensity=2,
                  rain_duration=timedelta(seconds=30*60),
                  event_type='EVENT',
                 ):
        
        # ADD TEMPORTAL EVENT INFORMAITON
        if event_type == 'LONG_TERM':
            self.event = LongTermMode(self.project_manager,
                                      self.db_session,
                                      self.project_directory,
                                      simulation_start=simulation_start,
                                      simulation_end=simulation_end,
                                      simulation_duration=simulation_duration,
                                     )
        else: # 'EVENT'
            self.event = EventMode(self.project_manager,
                                   self.db_session,
                                   self.project_directory,
                                   simulation_start=simulation_start,
                                   simulation_duration=simulation_duration,
                                   )
            self.event.add_uniform_precip_event(intensity=rain_intensity,
                                                duration=rain_duration)
1119793
def on_finish(self):
        
        super(StatsdMixin, self).on_finish()
        key = '%s.%s.%s.%s' % (self.__module__,
                               self.__class__.__name__,
                               self.request.method, self._status_code)
        LOGGER.info('Processing %s', key)
        self.statsd_incr(key)
        self.statsd_add_timing(key, self.request.request_time() * 1000)
302327
public void setDurationHistogram(java.util.Collection<HistogramEntry> durationHistogram) {
        if (durationHistogram == null) {
            this.durationHistogram = null;
            return;
        }

        this.durationHistogram = new java.util.ArrayList<HistogramEntry>(durationHistogram);
    }
361585
def end_timing(self, name, elapsed):
        
        counter = self.get(name, CounterType.Interval)
        self._calculate_stats(counter, elapsed)
        self._update()
1305410
def delayed_burst_run(self, target_cycles_per_sec):
        
        old_cycles = self.cycles
        start_time = time.time()

        self.burst_run()

        is_duration = time.time() - start_time
        new_cycles = self.cycles - old_cycles
        try:
            is_cycles_per_sec = new_cycles / is_duration
        except ZeroDivisionError:
            pass
        else:
            should_burst_duration = is_cycles_per_sec / target_cycles_per_sec
            target_duration = should_burst_duration * is_duration
            delay = target_duration - is_duration
            if delay > 0:
                if delay > self.max_delay:
                    self.delay = self.max_delay
                else:
                    self.delay = delay
                time.sleep(self.delay)

        self.call_sync_callbacks()
678992
def time( event )
      sync {stats[event].mark}
      yield
    ensure
      sync {stats[event].tick}
    end