当前位置: 首页>>代码示例>>Golang>>正文


Golang Time.Duration类代码示例

本文整理汇总了Golang中Time.Duration的典型用法代码示例。如果您正苦于以下问题:Golang Duration类的具体用法?Golang Duration怎么用?Golang Duration使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Duration类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestHistogramRotate

func TestHistogramRotate(t *testing.T) {
	defer TestingSetNow(nil)()
	setNow(0)
	h := NewHistogram(histWrapNum*time.Second, 1000+10*histWrapNum, 3)
	var cur time.Duration
	for i := 0; i < 3*histWrapNum; i++ {
		v := int64(10 * i)
		h.RecordValue(v)
		cur += time.Second
		setNow(cur)
		cur := h.Current()

		// When i == histWrapNum-1, we expect the entry from i==0 to move out
		// of the window (since we rotated for the histWrapNum'th time).
		expMin := int64((1 + i - (histWrapNum - 1)) * 10)
		if expMin < 0 {
			expMin = 0
		}

		if min := cur.Min(); min != expMin {
			t.Fatalf("%d: unexpected minimum %d, expected %d", i, min, expMin)
		}

		if max, expMax := cur.Max(), v; max != expMax {
			t.Fatalf("%d: unexpected maximum %d, expected %d", i, max, expMax)
		}
	}
}
开发者ID:cuongdo,项目名称:cockroach,代码行数:28,代码来源:metric_test.go

示例2: client

func client(wg *sync.WaitGroup, host string, port, len int, duration time.Duration, chStat chan int) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("error: %s", r)
		}
		log.Printf("disconnected")
		wg.Done()
	}()
	log.Printf("connecting to %s:%d, len %d, duration %s", host, port, len, duration.String())
	conn, err := utp.DialTimeout(fmt.Sprintf("%s:%d", host, port), time.Second)
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	log.Printf("connected")
	buf := bytes.Repeat([]byte("H"), len)
	ts := time.Now()
	for time.Since(ts) < duration {
		n, err := conn.Write(buf)
		if err != nil {
			if err == io.EOF {
				break
			}
			panic(err)
		}
		chStat <- n
	}
}
开发者ID:miolini,项目名称:utpbench,代码行数:28,代码来源:utpbench.go

示例3: timerLoop

func timerLoop(count *uint64, ticker *time.Ticker) {
	lastTime := time.Now().UTC()
	lastCount := *count
	zeroes := int8(0)
	var (
		msgsSent, newCount uint64
		elapsedTime        time.Duration
		now                time.Time
		rate               float64
	)
	for {
		_ = <-ticker.C
		newCount = *count
		now = time.Now()
		msgsSent = newCount - lastCount
		lastCount = newCount
		elapsedTime = now.Sub(lastTime)
		lastTime = now
		rate = float64(msgsSent) / elapsedTime.Seconds()
		if msgsSent == 0 {
			if newCount == 0 || zeroes == 3 {
				continue
			}
			zeroes++
		} else {
			zeroes = 0
		}
		log.Printf("Sent %d messages. %0.2f msg/sec\n", newCount, rate)
	}
}
开发者ID:pombredanne,项目名称:heka,代码行数:30,代码来源:main.go

示例4: Attack

// Attack reads its Targets from the passed Targeter and attacks them at
// the rate specified for duration time. Results are put into the returned channel
// as soon as they arrive.
func (a *Attacker) Attack(tr Targeter, rate uint64, du time.Duration) chan *Result {
	resc := make(chan *Result)
	throttle := time.NewTicker(time.Duration(1e9 / rate))
	hits := rate * uint64(du.Seconds())
	wrk := a.workers
	if wrk == 0 || wrk > hits {
		wrk = hits
	}
	share := hits / wrk

	var wg sync.WaitGroup
	for i := uint64(0); i < wrk; i++ {
		wg.Add(1)
		go func(share uint64) {
			defer wg.Done()
			for j := uint64(0); j < share; j++ {
				select {
				case tm := <-throttle.C:
					resc <- a.hit(tr, tm)
				case <-a.stop:
					return
				}
			}
		}(share)
	}

	go func() {
		wg.Wait()
		close(resc)
		throttle.Stop()
	}()

	return resc
}
开发者ID:cwinters,项目名称:vegeta,代码行数:37,代码来源:attack.go

示例5: Update

func (f Filter) Update(placement *Placement, sensors Sensors, dt time.Duration) {
	if f.AccGain+f.GyroGain != 1 {
		panic("Gains must add up to 1")
	}
	var (
		dts    = dt.Seconds()
		accDeg = PRY{
			Pitch: degAngle(sensors.Acc.Roll, sensors.Acc.Yaw),
			Roll:  degAngle(sensors.Acc.Pitch, sensors.Acc.Yaw),
		}
		gyroDeg = PRY{
			Pitch: placement.Pitch + (sensors.Gyro.Pitch * dts),
			Roll:  placement.Roll + (sensors.Gyro.Roll * dts),
			Yaw:   placement.Yaw + (sensors.Gyro.Yaw * dts),
		}
	)
	// Implements a simple complementation filter.
	// see http://www.pieter-jan.com/node/11
	placement.Pitch = gyroDeg.Pitch*f.GyroGain + accDeg.Pitch*f.AccGain
	placement.Roll = gyroDeg.Roll*f.GyroGain + accDeg.Roll*f.AccGain
	// @TODO Integrate gyro yaw with magotometer yaw
	placement.Yaw = gyroDeg.Yaw
	// The sonar sometimes reads very high values when on the ground. Ignoring
	// the sonar above a certain altitude solves the problem.
	// @TODO Use barometer above SonarMax
	if sensors.Sonar < f.SonarMax {
		placement.Altitude += (sensors.Sonar - placement.Altitude) * f.SonarGain
	}
}
开发者ID:vjeko,项目名称:godrone,代码行数:29,代码来源:filter.go

示例6: doShareUploadURL

// doShareUploadURL uploads files to the target.
func doShareUploadURL(objectURL string, isRecursive bool, expiry time.Duration, contentType string) *probe.Error {
	clnt, err := newClient(objectURL)
	if err != nil {
		return err.Trace(objectURL)
	}

	// Generate pre-signed access info.
	uploadInfo, err := clnt.ShareUpload(isRecursive, expiry, contentType)
	if err != nil {
		return err.Trace(objectURL, "expiry="+expiry.String(), "contentType="+contentType)
	}

	// Generate curl command.
	curlCmd := makeCurlCmd(objectURL, isRecursive, uploadInfo)

	printMsg(shareMesssage{
		ObjectURL:   objectURL,
		ShareURL:    curlCmd,
		TimeLeft:    expiry,
		ContentType: contentType,
	})

	// save shared URL to disk.
	return saveSharedURL(objectURL, curlCmd, expiry, contentType)
}
开发者ID:fwessels,项目名称:mc,代码行数:26,代码来源:share-upload-main.go

示例7: fetchExcessSharedDuration

// fetchExcessSharedDuration returns a slice of duration times (as seconds)
// given a distro and a map of DistroScheduleData, it traverses the map looking
// for alternate distros that are unable to meet maxDurationPerHost (turnaround)
// specification for shared tasks
func fetchExcessSharedDuration(distroScheduleData map[string]DistroScheduleData,
	distro string,
	maxDurationPerHost time.Duration) (sharedTasksDurationTimes []float64) {

	distroData := distroScheduleData[distro]

	// if we have more tasks to run than we have existing hosts and at least one
	// other alternate distro can not run all its shared scheduled and running tasks
	// within the maxDurationPerHost period, we need some more hosts for this distro
	for sharedDistro, sharedDuration := range distroData.sharedTasksDuration {
		if distro == sharedDistro {
			continue
		}

		alternateDistroScheduleData := distroScheduleData[sharedDistro]

		durationPerHost := alternateDistroScheduleData.totalTasksDuration /
			(float64(alternateDistroScheduleData.numExistingHosts) +
				float64(alternateDistroScheduleData.nominalNumNewHosts))

		// if no other alternate distro is able to meet the host requirements,
		// append its shared tasks duration time to the returned slice
		if durationPerHost > maxDurationPerHost.Seconds() {
			sharedTasksDurationTimes = append(sharedTasksDurationTimes,
				sharedDuration)
		}
	}
	return
}
开发者ID:himanshugpt,项目名称:evergreen,代码行数:33,代码来源:duration_based_host_allocator.go

示例8: NewIngestionProcess

// NewIngestionProcess creates a Process for ingesting data.
func NewIngestionProcess(git *gitinfo.GitInfo, tileDir, datasetName string, ri ingester.ResultIngester, config map[string]string, every time.Duration, nCommits int, minDuration time.Duration, statusDir, metricName string) ProcessStarter {
	return func() {
		i, err := ingester.NewIngester(git, tileDir, datasetName, ri, nCommits, minDuration, config, statusDir, metricName)
		if err != nil {
			glog.Fatalf("Failed to create Ingester: %s", err)
		}

		glog.Infof("Starting %s ingester. Run every %s.", datasetName, every.String())

		// oneStep is a single round of ingestion.
		oneStep := func() {
			glog.Infof("Running ingester: %s", datasetName)
			err := i.Update()
			if err != nil {
				glog.Error(err)
			}
			glog.Infof("Finished running ingester: %s", datasetName)
		}

		// Start the ingester.
		go func() {
			oneStep()
			for _ = range time.Tick(every) {
				oneStep()
			}
		}()
	}
}
开发者ID:Tiger66639,项目名称:skia-buildbot,代码行数:29,代码来源:main.go

示例9: TimerL

func TimerL(name string, duration time.Duration, rate float64) {
	if rand.Float64() > rate {
		return
	}

	HistogramL(name, float64(duration.Nanoseconds()/1000000), rate)
}
开发者ID:WIZARD-CXY,项目名称:golang-devops-stuff,代码行数:7,代码来源:Fsd.go

示例10: run

func run(name string) {
	var t, total time.Duration
	test, ok := tests[name]

	if !ok {
		fmt.Fprintf(os.Stderr, "test: `%s` does not exists\n", name)
		os.Exit(1)
	}

	fmt.Printf("%s:\n", strings.ToUpper(name))

	for i := 0; i < *R; i++ {
		if *mock {
			t = BenchmarkMock(test)
		} else {
			t = BenchmarkRedis(test)
		}

		total += t
		prints(t)
	}

	avg := time.Duration(total.Nanoseconds() / int64(*R))

	print("AVG ")
	printsA(avg, total)
	println()
}
开发者ID:simonz05,项目名称:godis,代码行数:28,代码来源:bench.go

示例11: newRestartFrequency

// newRestartFrequency returns an initialized restart frequency.
func newRestartFrequency(intensity int, period time.Duration) *restartFrequency {
	return &restartFrequency{
		intensity: intensity,
		period:    period.Nanoseconds(),
		restarts:  make([]int64, 0),
	}
}
开发者ID:rpeer-denis,项目名称:tcgl,代码行数:8,代码来源:supervisor.go

示例12: getOneTimeResourceUsageOnNode

// getOneTimeResourceUsageOnNode queries the node's /stats/container endpoint
// and returns the resource usage of targetContainers for the past
// cpuInterval.
// The acceptable range of the interval is 2s~120s. Be warned that as the
// interval (and #containers) increases, the size of kubelet's response
// could be sigificant. E.g., the 60s interval stats for ~20 containers is
// ~1.5MB. Don't hammer the node with frequent, heavy requests.
//
// cadvisor records cumulative cpu usage in nanoseconds, so we need to have two
// stats points to compute the cpu usage over the interval. Assuming cadvisor
// polls every second, we'd need to get N stats points for N-second interval.
// Note that this is an approximation and may not be accurate, hence we also
// write the actual interval used for calcuation (based on the timestampes of
// the stats points in containerResourceUsage.CPUInterval.
func getOneTimeResourceUsageOnNode(c *client.Client, nodeName string, cpuInterval time.Duration) (map[string]*containerResourceUsage, error) {
	numStats := int(float64(cpuInterval.Seconds()) / cadvisorStatsPollingIntervalInSeconds)
	if numStats < 2 || numStats > maxNumStatsToRequest {
		return nil, fmt.Errorf("numStats needs to be > 1 and < %d", maxNumStatsToRequest)
	}
	// Get information of all containers on the node.
	containerInfos, err := getContainerInfo(c, nodeName, &kubelet.StatsRequest{
		ContainerName: "/",
		NumStats:      numStats,
		Subcontainers: true,
	})
	if err != nil {
		return nil, err
	}
	// Process container infos that are relevant to us.
	usageMap := make(map[string]*containerResourceUsage, len(targetContainers))
	for _, name := range targetContainers {
		info, ok := containerInfos[name]
		if !ok {
			return nil, fmt.Errorf("missing info for container %q on node %q", name, nodeName)
		}
		first := info.Stats[0]
		last := info.Stats[len(info.Stats)-1]
		usageMap[name] = computeContainerResourceUsage(name, first, last)
	}
	return usageMap, nil
}
开发者ID:jmferrer,项目名称:kubernetes,代码行数:41,代码来源:kubelet_stats.go

示例13: StartHeartbeats

func StartHeartbeats(localIp string, ttl time.Duration, config *config.Config, storeAdapter storeadapter.StoreAdapter, logger *gosteno.Logger) (stopChan chan (chan bool)) {
	if len(config.EtcdUrls) == 0 {
		return
	}

	if storeAdapter == nil {
		panic("store adapter is nil")
	}

	logger.Debugf("Starting Health Status Updates to Store: /healthstatus/doppler/%s/%s/%d", config.Zone, config.JobName, config.Index)
	status, stopChan, err := storeAdapter.MaintainNode(storeadapter.StoreNode{
		Key:   fmt.Sprintf("/healthstatus/doppler/%s/%s/%d", config.Zone, config.JobName, config.Index),
		Value: []byte(localIp),
		TTL:   uint64(ttl.Seconds()),
	})

	if err != nil {
		panic(err)
	}

	go func() {
		for stat := range status {
			logger.Debugf("Health updates channel pushed %v at time %v", stat, time.Now())
		}
	}()

	return stopChan
}
开发者ID:JimmyMa,项目名称:loggregator,代码行数:28,代码来源:main.go

示例14: isHealthyOffsetInterval

// isHealthyOffsetInterval returns true if the ClusterOffsetInterval indicates
// that the node's offset is within maxOffset, else false. For example, if the
// offset interval is [-20, -11] and the maxOffset is 10 nanoseconds, then the
// clock offset must be too great, because no point in the interval is within
// the maxOffset.
func isHealthyOffsetInterval(i ClusterOffsetInterval, maxOffset time.Duration) bool {
	if i.Lowerbound > maxOffset.Nanoseconds() ||
		i.Upperbound < -maxOffset.Nanoseconds() {
		return false
	}
	return true
}
开发者ID:mbertschler,项目名称:cockroach,代码行数:12,代码来源:clock_offset.go

示例15: DoBatchRecording

func (s *Server) DoBatchRecording(name string, past time.Duration) (id string, err error) {
	v := url.Values{}
	v.Add("type", "batch")
	v.Add("name", name)
	v.Add("past", past.String())
	r, err := http.Post(s.URL()+"/record?"+v.Encode(), "", nil)
	if err != nil {
		return
	}
	defer r.Body.Close()
	if r.StatusCode != http.StatusOK {
		err = fmt.Errorf("unexpected status code got %d exp %d", r.StatusCode, http.StatusOK)
		return
	}

	// Decode valid response
	type resp struct {
		RecordingID string `json:"RecordingID"`
		Error       string `json:"Error"`
	}
	rp := resp{}
	d := json.NewDecoder(r.Body)
	d.Decode(&rp)
	if rp.Error != "" {
		err = errors.New(rp.Error)
		return
	}
	id = rp.RecordingID
	v = url.Values{}
	v.Add("id", id)
	_, err = s.HTTPGet(s.URL() + "/record?" + v.Encode())
	return
}
开发者ID:sstarcher,项目名称:kapacitor,代码行数:33,代码来源:server_helper_test.go


注:本文中的Time.Duration类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。