Reports a sampling (timer, histogram) metric.
@param name The name.
@param sampled The sampled metric.
@param isDuration Is this a duration.
976734
private void reportSampled(final String name,
                              final Sampling sampled,
                              final boolean isDuration) {
      EnumSet<MetricField> fields = reportedMetrics.get(name);
      if(fields == null) {
         return;
      }

      String nrName = isDuration ? buildDuration(name) : buildName(name);

      if(fields.contains(MetricField.MEDIAN)) {
         NewRelic.recordMetric(nrName, (float)sampled.getSnapshot().getMedian());
      }

      if(fields.contains(MetricField.MAX)) {
         NewRelic.recordMetric(nrName, (float)sampled.getSnapshot().getMax());
      }

      if(fields.contains(MetricField.MIN)) {
         NewRelic.recordMetric(nrName, (float)sampled.getSnapshot().getMin());
      }

      if(fields.contains(MetricField.P75)) {
         NewRelic.recordMetric(nrName, (float)sampled.getSnapshot().get75thPercentile());
      }

      if(fields.contains(MetricField.P95)) {
         NewRelic.recordMetric(nrName, (float)sampled.getSnapshot().get95thPercentile());
      }

      if(fields.contains(MetricField.P98)) {
         NewRelic.recordMetric(nrName, (float)sampled.getSnapshot().get98thPercentile());
      }

      if(fields.contains(MetricField.P99)) {
         NewRelic.recordMetric(nrName, (float)sampled.getSnapshot().get99thPercentile());
      }

      if(fields.contains(MetricField.P999)) {
         NewRelic.recordMetric(nrName, (float)sampled.getSnapshot().get999thPercentile());
      }

      if(fields.contains(MetricField.STD)) {
         NewRelic.recordMetric(nrName, (float)sampled.getSnapshot().getStdDev());
      }
   }
659644
@Override
  public final void sample()
  {
    long totalCount = _totalCount.get();
    long lastTotal = _lastTotal;
    _lastTotal = totalCount;

    _value = totalCount - lastTotal;
  }
1316236
function checkDuration (val, name, vnode) {
  if (typeof val !== 'number') {
    warn(
      "<transition> explicit " + name + " duration is not a valid number - " +
      "got " + (JSON.stringify(val)) + ".",
      vnode.context
    );
  } else if (isNaN(val)) {
    warn(
      "<transition> explicit " + name + " duration is NaN - " +
      'the duration expression might be incorrect.',
      vnode.context
    );
  }
}
1176433
public void endTiming(String name, float elapsed) {
		for (ICounters counter : _counters) {
			if (counter instanceof ITimingCallback)
				((ITimingCallback) counter).endTiming(name, elapsed);
		}
	}
748182
Timer timer(Meter.Id id, DistributionStatisticConfig distributionStatisticConfig, PauseDetector pauseDetectorOverride) {
        return registerMeterIfNecessary(Timer.class, id, distributionStatisticConfig, (id2, filteredConfig) -> {
            Meter.Id withUnit = id2.withBaseUnit(getBaseTimeUnitStr());
            return newTimer(withUnit, filteredConfig.merge(defaultHistogramConfig()), pauseDetectorOverride);
        }, NoopTimer::new);
    }
376647
public static function stopMeasure($name): void
    {
        if (self::$debugbar instanceof StandardDebugBar) {
            $collector = self::$debugbar->getCollector('time');

            if ($collector instanceof TimeDataCollector) {
                $collector->stopMeasure($name);
            }
        }
    }
949116
@Override
  public void reportMetric(final IMetric<?> metric) throws MetricException {
    final String metricName = metric.getName();
    if (!this.historyListMapping.containsKey(metricName)) {
      logger.info("First time capturing metric: " + metricName);
      this.historyListMapping.put(metricName, new LinkedBlockingDeque<>());
    }
    synchronized (this.historyListMapping.get(metricName)) {
      logger.debug("Ingesting metric: " + metricName);
      this.historyListMapping.get(metricName).add(new InMemoryHistoryNode(metric.getValue()));
      cleanUsingTime(metricName, this.historyListMapping.get(metricName).peekLast().getTimestamp());
    }
  }
202739
public void setOriginalAppenderName(String name) {
        this.originalAppenderName = name;
        this.initBatcher(this.originalAppenderName);
        this.putBufferTimeTracer = Monitors.newTimer("putBuffer",
                TimeUnit.NANOSECONDS);
        this.putDiscardMapTimeTracer = Monitors.newTimer("putDiscardMap",
                TimeUnit.NANOSECONDS);
        this.locationInfoTimer = Monitors.newTimer("locationInfo",
                TimeUnit.NANOSECONDS);
        this.saveThreadLocalTimer = Monitors.newTimer("saveThreadLocal",
                TimeUnit.NANOSECONDS);

        // We register these counters differently to the above timers, because need to keep the metric names as they were when we were
        // using DynamicCounter.increment() directly.
        this.summarizeEventCounter = initAndRegisterCounter(this.originalAppenderName + "_summarizeEvent");
        this.discardEventCounter = initAndRegisterCounter(this.originalAppenderName + "_discardEvent");
        this.putInBufferCounter = initAndRegisterCounter(this.originalAppenderName + "_putInBuffer");

        this.logSummaryMap = CacheBuilder
                .newBuilder()
                .initialCapacity(5000)
                .maximumSize(
                        CONFIGURATION.getLogSummarySize(originalAppenderName))
                .expireAfterWrite(
                        CONFIGURATION
                                .getLogSummaryExpiry(originalAppenderName),
                        TimeUnit.SECONDS).<String, LogSummary> build().asMap();
        try {
            Monitors.registerObject(this.originalAppenderName, this);
        } catch (Throwable e) {
            if (CONFIGURATION.shouldPrintLoggingErrors()) {
                System.err.println("Cannot register monitor for AsyncAppender "
                        + this.originalAppenderName);
                e.printStackTrace();
            }
        }
    }
381847
def _submit_gauges_from_histogram(
        self, name, metric, send_histograms_buckets=True, custom_tags=None, hostname=None
    ):
        
        if custom_tags is None:
            custom_tags = []
        # histograms do not have a value attribute
        val = getattr(metric, self.METRIC_TYPES[4]).sample_count
        if self._is_value_valid(val):
            self._submit_gauge("{}.count".format(name), val, metric, custom_tags)
        else:
            self.log.debug("Metric value is not supported for metric {}.count.".format(name))
        val = getattr(metric, self.METRIC_TYPES[4]).sample_sum
        if self._is_value_valid(val):
            self._submit_gauge("{}.sum".format(name), val, metric, custom_tags)
        else:
            self.log.debug("Metric value is not supported for metric {}.sum.".format(name))
        if send_histograms_buckets:
            for bucket in getattr(metric, self.METRIC_TYPES[4]).bucket:
                val = bucket.cumulative_count
                limit = bucket.upper_bound
                if self._is_value_valid(val):
                    self._submit_gauge(
                        "{}.count".format(name),
                        val,
                        metric,
                        custom_tags=custom_tags + ["upper_bound:{}".format(limit)],
                        hostname=hostname,
                    )
                else:
                    self.log.debug("Metric value is not supported for metric {}.count.".format(name))
1022415
public void record(double sample, TimeUnit timeUnit) {
        rotate();
        final long sampleNanos = (long) TimeUtils.convert(sample, timeUnit, TimeUnit.NANOSECONDS);
        for (AtomicLong max : ringBuffer) {
            updateMax(max, sampleNanos);
        }
    }
2844
public ResourceModelStatistics countMappingDuration(int durationInMs) {
        // The right-hand interval boundaries are pre-calculated. We start at the smallest (1) of the
        // interval [0, 1). Thus, when our value is less than the boundary, we know it is in the current interval (i),
        // as the right-hand boundary is exclusive.
        for (int i = 0; i < this.indexBoundaries.length; ++i) {
            if (durationInMs < this.indexBoundaries[i]) {
                ++this.mappingDurationFrequencies[i];
                return this;
            }
        }

        // The mapping duration time exceeds the frequency table boundaries.
        // Fallback: count it as the longest possible duration
        ++this.mappingDurationFrequencies[this.mappingDurationFrequencies.length - 1];
        return this;
    }
1033285
public final void sample()
  {
    long count = _count.get();
    long lastCount = _lastAvgCount.getAndSet(count);
    long time = _time.get();
    long lastTime = _lastAvgTime.getAndSet(time);

    if (count == lastCount)
      _value = 0;
    else
      _value = _scale * (time - lastTime) / (double) (count - lastCount);
  }
1118278
@Override
	public TimelineSample<StopwatchTimeRange> sample() {
		StopwatchTimeRange[] timeRangesCopy;
		synchronized (this) {
			timeRangesCopy = timeRanges.toArray(new StopwatchTimeRange[timeRanges.size()]);
		}
		// TODO sample each time-range by making a copy of it
		return new TimelineSample<>(timeRanges.getCapacity(), timeRangeWidth * SimonClock.NANOS_IN_MILLIS, timeRangesCopy);
	}
203830
MetricFamilySamples fromHistogram(String dropwizardName, Histogram histogram) {
        return fromSnapshotAndCount(dropwizardName, histogram.getSnapshot(), histogram.getCount(), 1.0,
                getHelpMessage(dropwizardName, histogram));
    }
531417
public void report() {
        if (log.isTraceEnabled()) {
            log.trace(String.format("Timers avg (ms): model=%.1f inf=%.1f val=%.1f grad=%.1f", 
                    updTimer.avgMs(), infTimer.avgMs(), valTimer.avgMs(), gradTimer.avgMs()));
        }
        double sum = initTimer.totMs() + updTimer.totMs() + infTimer.totMs() + valTimer.totMs() + gradTimer.totMs();
        double mult = 100.0 / sum;
        log.debug(String.format("Timers: init=%.1f%% model=%.1f%% inf=%.1f%% val=%.1f%% grad=%.1f%% avg(ms)=%.1f max(ms)=%.1f stddev(ms)=%.1f", 
                initTimer.totMs()*mult, updTimer.totMs()*mult, infTimer.totMs()*mult, valTimer.totMs()*mult, gradTimer.totMs()*mult,
                tot.avgMs(), tot.maxSplitMs(), tot.stdDevMs()));
    }
1212179
static MetricFamilySamples createDescribableMetricFamilySamples(
      MetricDescriptor metricDescriptor, String namespace) {
    String name = getNamespacedName(metricDescriptor.getName(), namespace);
    Type type = getType(metricDescriptor.getType());
    List<String> labelNames = convertToLabelNames(metricDescriptor.getLabelKeys());

    if (containsDisallowedLeLabelForHistogram(labelNames, type)) {
      throw new IllegalStateException(
          "Prometheus Histogram cannot have a label named 'le', "
              + "because it is a reserved label for bucket boundaries. "
              + "Please remove this key from your view.");
    }

    if (containsDisallowedQuantileLabelForSummary(labelNames, type)) {
      throw new IllegalStateException(
          "Prometheus Summary cannot have a label named 'quantile', "
              + "because it is a reserved label. Please remove this key from your view.");
    }

    return new MetricFamilySamples(
        name, type, metricDescriptor.getDescription(), Collections.<Sample>emptyList());
  }
1355341
public static void main(String[] args) {
        MeterRegistry registry = SampleConfig.myMonitoringSystem();

        Timer timer = Timer.builder("timer")
            .publishPercentiles(0.5, 0.95)
            .register(registry);

        Object placeholder = new Object();
        AtomicLong totalTimeNanos = new AtomicLong(0);
        AtomicLong totalCount = new AtomicLong(0);

        FunctionTimer.builder("ftimer", placeholder, p -> totalCount.get(), p -> totalTimeNanos.get(), TimeUnit.NANOSECONDS)
            .register(registry);

        RandomEngine r = new MersenneTwister64(0);
        Normal incomingRequests = new Normal(0, 1, r);
        Normal duration = new Normal(250, 50, r);

        AtomicInteger latencyForThisSecond = new AtomicInteger(duration.nextInt());
        Flux.interval(Duration.ofSeconds(1))
            .doOnEach(d -> latencyForThisSecond.set(duration.nextInt()))
            .subscribe();

        // the potential for an "incoming request" every 10 ms
        Flux.interval(Duration.ofMillis(10))
            .doOnEach(d -> {
                if (incomingRequests.nextDouble() + 0.4 > 0) {
                    // pretend the request took some amount of time, such that the time is
                    // distributed normally with a mean of 250ms
                    timer.record(latencyForThisSecond.get(), TimeUnit.MILLISECONDS);
                    totalCount.incrementAndGet();
                    totalTimeNanos.addAndGet((long) TimeUtils.millisToUnit(latencyForThisSecond.get(), TimeUnit.NANOSECONDS));
                }
            })
            .blockLast();
    }