1// Copyright 2014 The Prometheus Authors
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14package prometheus_test
15
16import (
17	"os"
18
19	"github.com/prometheus/client_golang/prometheus"
20)
21
22var (
23	// If a function is called rarely (i.e. not more often than scrapes
24	// happen) or ideally only once (like in a batch job), it can make sense
25	// to use a Gauge for timing the function call. For timing a batch job
26	// and pushing the result to a Pushgateway, see also the comprehensive
27	// example in the push package.
28	funcDuration = prometheus.NewGauge(prometheus.GaugeOpts{
29		Name: "example_function_duration_seconds",
30		Help: "Duration of the last call of an example function.",
31	})
32)
33
34func run() error {
35	// The Set method of the Gauge is used to observe the duration.
36	timer := prometheus.NewTimer(prometheus.ObserverFunc(funcDuration.Set))
37	defer timer.ObserveDuration()
38
39	// Do something. Return errors as encountered. The use of 'defer' above
40	// makes sure the function is still timed properly.
41	return nil
42}
43
44func ExampleTimer_gauge() {
45	if err := run(); err != nil {
46		os.Exit(1)
47	}
48}
49