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


Golang Time.Sub方法代码示例

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


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

示例1: nextSleep

func (a *Attempt) nextSleep(now time.Time) time.Duration {
	sleep := a.strategy.Delay - now.Sub(a.last)
	if sleep < 0 {
		return 0
	}
	return sleep
}
开发者ID:devick,项目名称:flynn,代码行数:7,代码来源:attempt.go

示例2: loopFetchOnly

// loopFetchOnly is a version of loop that includes only the logic
// that calls Fetch.
func (s *sub) loopFetchOnly() {
	// STARTFETCHONLY OMIT
	var pending []Item // appended by fetch; consumed by send
	var next time.Time // initially January 1, year 0
	var err error
	for {
		var fetchDelay time.Duration // initally 0 (no delay)
		if now := time.Now(); next.After(now) {
			fetchDelay = next.Sub(now)
		}
		startFetch := time.After(fetchDelay)

		select {
		case <-startFetch:
			var fetched []Item
			fetched, next, err = s.fetcher.Fetch()
			if err != nil {
				next = time.Now().Add(10 * time.Second)
				break
			}
			pending = append(pending, fetched...)
		}
	}
	// STOPFETCHONLY OMIT
}
开发者ID:dylanpoe,项目名称:golang.org,代码行数:27,代码来源:dedupermain.go

示例3: compareTime

// compareTime checks if a and b are roughly equal
func compareTime(a time.Time, b time.Time) bool {
	diff := a.Sub(b)
	if diff < 0 {
		diff = -diff
	}
	return diff < precision
}
开发者ID:intelsdi-x,项目名称:rkt,代码行数:8,代码来源:rkt_list_test.go

示例4: minExpiry

// minExpiry returns a minimal expiry. A minimal expiry is the larger on
// between now + minLeaseTerm and the given expectedExpiry.
func minExpiry(now time.Time, expectedExpiry time.Time) time.Time {
	minExpiry := time.Now().Add(minLeaseTerm)
	if expectedExpiry.Sub(minExpiry) < 0 {
		expectedExpiry = minExpiry
	}
	return expectedExpiry
}
开发者ID:jnan77,项目名称:etcd,代码行数:9,代码来源:lessor.go

示例5: delta

// delta returns the elapsed time since the last event or the trace start,
// and whether it spans midnight.
// L >= tr.mu
func (tr *trace) delta(t time.Time) (time.Duration, bool) {
	if len(tr.events) == 0 {
		return t.Sub(tr.Start), false
	}
	prev := tr.events[len(tr.events)-1].When
	return t.Sub(prev), prev.Day() != t.Day()
}
开发者ID:lrita,项目名称:etcd,代码行数:10,代码来源:trace.go

示例6: TestAccuracy

func TestAccuracy(t *testing.T) {
	var count int64
	var i int64
	count = 100
	var tstart time.Time
	var tend time.Time
	var td int64
	var tsum int64
	tdarr := make([]int64, count)
	for i = 0; i < count; i++ {
		tstart = time.Now()
		time.Sleep(1 * time.Second)
		tend = time.Now()
		td = tend.Sub(tstart).Nanoseconds()
		//fmt.Printf("%d ", td)
		tdarr[i] = td
		tsum += td
	}
	var mean float64 = float64(tsum) / float64(count)
	vari := float64(0)
	for i = 0; i < count; i++ {
		x := float64(tdarr[i]) - float64(mean)
		vari += x * x
	}
	vari = vari / float64(count-1)
	fmt.Printf("mean: %v\n", mean)
	fmt.Printf("variance: %v\n", vari)
	fmt.Printf("stddev: %v\n", math.Sqrt(float64(vari)))
	//fmt.Println(tdarr)
}
开发者ID:jpfairbanks,项目名称:timing,代码行数:30,代码来源:timing_test.go

示例7: PrintSummary

// PrintSummary ...
func PrintSummary(buildRunResults models.BuildRunResultsModel) {
	iconBoxWidth := len("    ")
	timeBoxWidth := len(" time (s) ")
	titleBoxWidth := stepRunSummaryBoxWidthInChars - 4 - iconBoxWidth - timeBoxWidth

	fmt.Println()
	fmt.Println()
	log.Infof("+%s+", strings.Repeat("-", stepRunSummaryBoxWidthInChars-2))
	whitespaceWidth := (stepRunSummaryBoxWidthInChars - 2 - len("bitrise summary")) / 2
	log.Infof("|%sbitrise summary%s|", strings.Repeat(" ", whitespaceWidth), strings.Repeat(" ", whitespaceWidth))
	log.Infof("+%s+%s+%s+", strings.Repeat("-", iconBoxWidth), strings.Repeat("-", titleBoxWidth), strings.Repeat("-", timeBoxWidth))

	whitespaceWidth = stepRunSummaryBoxWidthInChars - len("|    | title") - len("| time (s) |")
	log.Infof("|    | title%s| time (s) |", strings.Repeat(" ", whitespaceWidth))
	log.Infof("+%s+%s+%s+", strings.Repeat("-", iconBoxWidth), strings.Repeat("-", titleBoxWidth), strings.Repeat("-", timeBoxWidth))

	orderedResults := buildRunResults.OrderedResults()
	tmpTime := time.Time{}
	for _, stepRunResult := range orderedResults {
		tmpTime = tmpTime.Add(stepRunResult.RunTime)
		log.Info(stepResultCell(stepRunResult))
	}
	runtime := tmpTime.Sub(time.Time{})

	log.Infof("+%s+", strings.Repeat("-", stepRunSummaryBoxWidthInChars-2))

	runtimeStr := TimeToFormattedSeconds(runtime, " sec")
	whitespaceWidth = stepRunSummaryBoxWidthInChars - len(fmt.Sprintf("| Total runtime: %s|", runtimeStr))
	log.Infof("| Total runtime: %s%s|", runtimeStr, strings.Repeat(" ", whitespaceWidth))
	log.Infof("+%s+", strings.Repeat("-", stepRunSummaryBoxWidthInChars-2))

	fmt.Println()
}
开发者ID:bitrise-io,项目名称:bitrise-yml-converter,代码行数:34,代码来源:print.go

示例8: validTokenAtTime

// validTokenAtTime reports whether a token is valid at the given time.
func validTokenAtTime(token, key, userID, actionID string, now time.Time) bool {
	// Extract the issue time of the token.
	sep := strings.LastIndex(token, ":")
	if sep < 0 {
		return false
	}
	millis, err := strconv.ParseInt(token[sep+1:], 10, 64)
	if err != nil {
		return false
	}
	issueTime := time.Unix(0, millis*1e6)

	// Check that the token is not expired.
	if now.Sub(issueTime) >= Timeout {
		return false
	}

	// Check that the token is not from the future.
	// Allow 1 minute grace period in case the token is being verified on a
	// machine whose clock is behind the machine that issued the token.
	if issueTime.After(now.Add(1 * time.Minute)) {
		return false
	}

	expected := generateTokenAtTime(key, userID, actionID, issueTime)

	// Check that the token matches the expected value.
	// Use constant time comparison to avoid timing attacks.
	return subtle.ConstantTimeCompare([]byte(token), []byte(expected)) == 1
}
开发者ID:Rudloff,项目名称:platform,代码行数:31,代码来源:xsrf.go

示例9: lookupIPDeadline

// lookupIPDeadline looks up a hostname with a deadline.
func lookupIPDeadline(host string, deadline time.Time) (addrs []IPAddr, err error) {
	if deadline.IsZero() {
		return lookupIPMerge(host)
	}

	// We could push the deadline down into the name resolution
	// functions.  However, the most commonly used implementation
	// calls getaddrinfo, which has no timeout.

	timeout := deadline.Sub(time.Now())
	if timeout <= 0 {
		return nil, errTimeout
	}
	t := time.NewTimer(timeout)
	defer t.Stop()

	ch := lookupGroup.DoChan(host, func() (interface{}, error) {
		return testHookLookupIP(lookupIP, host)
	})

	select {
	case <-t.C:
		// The DNS lookup timed out for some reason.  Force
		// future requests to start the DNS lookup again
		// rather than waiting for the current lookup to
		// complete.  See issue 8602.
		lookupGroup.Forget(host)

		return nil, errTimeout

	case r := <-ch:
		return lookupIPReturn(r.Val, r.Err, r.Shared)
	}
}
开发者ID:RajibTheKing,项目名称:gcc,代码行数:35,代码来源:lookup.go

示例10: toNtpTime

// toNtpTime converts the time value t into an ntpTime representation.
func toNtpTime(t time.Time) ntpTime {
	nsec := uint64(t.Sub(ntpEpoch))
	return ntpTime{
		Seconds:  uint32(nsec / nanoPerSec),
		Fraction: uint32((nsec % nanoPerSec) << 32 / nanoPerSec),
	}
}
开发者ID:Jean-Daniel,项目名称:node_exporter,代码行数:8,代码来源:ntp.go

示例11: Latest

// Latest returns the latest local time after which we can be confident that
// the remote writer will agree the supplied time is in the past.
func (skew Skew) Latest(remote time.Time) (local time.Time) {
	if skew.isZero() {
		return remote
	}
	delta := remote.Sub(skew.LastWrite)
	return skew.End.Add(delta)
}
开发者ID:howbazaar,项目名称:juju,代码行数:9,代码来源:skew.go

示例12: Earliest

// Earliest returns the earliest local time after which we can be confident
// that the remote writer will agree the supplied time is in the past.
func (skew Skew) Earliest(remote time.Time) (local time.Time) {
	if skew.isZero() {
		return remote
	}
	delta := remote.Sub(skew.LastWrite)
	return skew.Beginning.Add(delta)
}
开发者ID:howbazaar,项目名称:juju,代码行数:9,代码来源:skew.go

示例13: NextExpected

// NextExpected returns duration (relative to now) until the next expected event
// given the state of a, the fact that no new event happened until
// now, and assuming the event source is a Poisson process with a mean
// interval time much smaller than our Tau.
func (a Counter) NextExpected(now time.Time) time.Duration {
	if a.Value <= 0 {
		return time.Duration(math.MaxInt64)
	}
	delta := float64(now.Sub(a.Timestamp)) / float64(a.Tau)          // discount activity till now
	return time.Duration(math.Exp(delta) * float64(a.Tau) / a.Value) // tau/(value * exp(-d))
}
开发者ID:lvdlvd,项目名称:go-activity,代码行数:11,代码来源:activity.go

示例14: Writer

// Writer reads rows from ch and writes them to
// the underlying Collection
func (b *Benchmark) Writer(ch chan []*Row) {
	n := int64(0)        // row set counter
	ns := int64(0)       // elapsed time in nanoseconds
	var t0, t1 time.Time // time between arrivals
	for rows := range ch {
		n, t1 = n+1, time.Now()
		if n > 1 {
			ns += t1.Sub(t0).Nanoseconds()
		}
		t0 = t1

		if b.mu != nil {
			b.mu.Lock()
		}
		err := b.c.Set(rows)
		if b.mu != nil {
			b.mu.Unlock()
		}

		if err != nil {
			log.Println(err)
			return
		}
	}

	b.done <- true
	if n > 0 {
		log.Printf("%d row sets arrived at an average inter-arrival rate of %s",
			n, time.Duration(ns/n))
	}
}
开发者ID:jimrobinson,项目名称:kvbench,代码行数:33,代码来源:benchmark.go

示例15: estimateTps

// estimateTps estimates the average transactions per second of
// the simulation.
func (com *Communication) estimateTps(tpsChan chan<- float64, txCurve map[int32]*Row) {
	defer com.wg.Done()

	var first, last time.Time
	var diff, curveDiff time.Duration
	var txnCount, curveCount, block int
	firstTx := true

	for {
		select {
		case last = <-com.timeReceived:
			if firstTx {
				first = last
				firstTx = false
			}
			txnCount++
			diff = last.Sub(first)

			curveCount++
			if c, ok := txCurve[int32(block)]; ok && curveCount == c.txCount {
				// A block has been mined; reset necessary variables
				curveCount = 0
				firstTx = true
				curveDiff += diff
				diff = curveDiff
				// Use next block's desired transaction count
				block++
			}
		case <-com.exit:
			tpsChan <- float64(txnCount) / diff.Seconds()
			return
		}
	}
}
开发者ID:stormasm,项目名称:btcsim1020,代码行数:36,代码来源:comm.go


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