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


Golang Duration.Seconds方法代码示例

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


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

示例1: durationUnit

func (t *Timer) durationUnit(dur time.Duration) float64 {
	sec := dur.Seconds()
	if t.TimeUnit == "ms" {
		return sec * 1000
	}
	return sec
}
开发者ID:ericcapricorn,项目名称:flynn,代码行数:7,代码来源:timer.go

示例2: Print

func (b *Boom) Print() {
	total := b.end.Sub(b.start)
	var avgTotal float64
	var fastest, slowest time.Duration

	for {
		select {
		case r := <-b.results:
			latencies = append(latencies, r.duration.Seconds())
			statusCodeDist[r.statusCode]++

			avgTotal += r.duration.Seconds()
			if fastest.Nanoseconds() == 0 || r.duration.Nanoseconds() < fastest.Nanoseconds() {
				fastest = r.duration
			}
			if r.duration.Nanoseconds() > slowest.Nanoseconds() {
				slowest = r.duration
			}
		default:
			rps := float64(b.N) / total.Seconds()
			fmt.Printf("\nSummary:\n")
			fmt.Printf("  Total:\t%4.4f secs.\n", total.Seconds())
			fmt.Printf("  Slowest:\t%4.4f secs.\n", slowest.Seconds())
			fmt.Printf("  Fastest:\t%4.4f secs.\n", fastest.Seconds())
			fmt.Printf("  Average:\t%4.4f secs.\n", avgTotal/float64(b.N))
			fmt.Printf("  Requests/sec:\t%4.4f\n", rps)
			fmt.Printf("  Speed index:\t%v\n", speedIndex(rps))
			sort.Float64s(latencies)
			b.printHistogram()
			b.printLatencies()
			b.printStatusCodes()
			return
		}
	}
}
开发者ID:kkbankol,项目名称:boom,代码行数:35,代码来源:print.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: retryRequest

func (p *PushProcessor) retryRequest(req *Request, retryAfter time.Duration, subscriber string, psp *PushServiceProvider, dp *DeliveryPoint) {
	if req.nrRetries >= p.max_nr_retry {
		return
	}
	newreq := new(Request)
	newreq.nrRetries = req.nrRetries + 1
	newreq.PreviousTry = req
	newreq.ID = req.ID
	newreq.Action = ACTION_PUSH
	newreq.PushServiceProvider = psp
	newreq.DeliveryPoint = dp
	newreq.RequestSenderAddr = req.RequestSenderAddr
	newreq.Notification = req.Notification

	newreq.Service = req.Service
	newreq.Subscribers = make([]string, 1)
	newreq.Subscribers[0] = subscriber
	newreq.PunchTimestamp()

	if req.nrRetries == 0 || req.backoffTime == 0 {
		newreq.backoffTime = init_backoff_time
	} else {
		newreq.backoffTime = req.backoffTime << 1
	}

	waitTime := newreq.backoffTime
	if retryAfter > 0*time.Second {
		waitTime = int64(retryAfter.Seconds())
	}

	duration := time.Duration(time.Duration(waitTime) * time.Second)
	time.Sleep(duration)
	p.backendch <- newreq
}
开发者ID:NoahShen,项目名称:uniqush-push,代码行数:34,代码来源:pushprocessor.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: runContainerTimed

func runContainerTimed(name string,
	args []string,
	wd string,
	stdin io.Reader,
	stdout io.Writer,
	stderr io.Writer,
	timeout time.Duration) error {

	sec := fmt.Sprintf("%d", int(timeout.Seconds()))
	args = append([]string{"-k", "1", sec, name}, args...)
	err := runContainer("timeout",
		args,
		wd,
		stdin,
		stdout,
		stderr)

	start := time.Now()
	if err != nil {
		if ee, ok := err.(*exec.ExitError); ok {
			pst := ee.ProcessState
			if st, ok := pst.Sys().(syscall.WaitStatus); ok {
				if st.ExitStatus() == 124 {
					err = fmt.Errorf("program killed after %s",
						time.Now().Sub(start).String())
				}
			}
		}
		return err
	}

	return nil
}
开发者ID:fluter01,项目名称:lotsawa,代码行数:33,代码来源:sandbox.go

示例9: 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

示例10: 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 {
	workers := &sync.WaitGroup{}
	results := make(chan *Result)
	ticks := make(chan time.Time)
	for i := uint64(0); i < a.workers; i++ {
		go a.attack(tr, workers, ticks, results)
	}

	go func() {
		defer close(results)
		defer workers.Wait()
		defer close(ticks)
		interval := 1e9 / rate
		hits := rate * uint64(du.Seconds())
		for began, done := time.Now(), uint64(0); done < hits; done++ {
			now, next := time.Now(), began.Add(time.Duration(done*interval))
			time.Sleep(next.Sub(now))
			select {
			case ticks <- max(next, now):
			case <-a.stopch:
				return
			default: // all workers are blocked. start one more and try again
				go a.attack(tr, workers, ticks, results)
				done--
			}
		}
	}()

	return results
}
开发者ID:masahide,项目名称:vegeta-memcached,代码行数:33,代码来源:attack.go

示例11: timerLoop

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

示例12: publishContainer

// publishContainer publishes the docker container to etcd.
func (s *Server) publishContainer(container *docker.APIContainers, ttl time.Duration) {
	r := regexp.MustCompile(appNameRegex)
	for _, name := range container.Names {
		// HACK: remove slash from container name
		// see https://github.com/docker/docker/issues/7519
		containerName := name[1:]
		match := r.FindStringSubmatch(containerName)
		if match == nil {
			continue
		}
		appName := match[1]
		appPath := fmt.Sprintf("%s/%s", appName, containerName)
		keyPath := fmt.Sprintf("/deis/services/%s", appPath)
		for _, p := range container.Ports {
			// lowest port wins (docker sorts the ports)
			// TODO (bacongobbler): support multiple exposed ports
			port := strconv.Itoa(int(p.PublicPort))
			hostAndPort := s.host + ":" + port
			if s.IsPublishableApp(containerName) && s.IsPortOpen(hostAndPort) {
				s.setEtcd(keyPath, hostAndPort, uint64(ttl.Seconds()))
				safeMap.Lock()
				safeMap.data[container.ID] = appPath
				safeMap.Unlock()
			}
			break
		}
	}
}
开发者ID:gpxl,项目名称:deis,代码行数:29,代码来源:publisher.go

示例13: update

// update polls user input, runs physics, calls application update, and
// finally refreshes all models resulting in updated transforms.
// The transform hierarchy is now ready to generate a render frame.
func (eng *engine) update(app App, dt time.Duration, ut uint64) {

	// Fetch input from the device thread. Essentially a sequential call.
	eng.machine <- eng.data // blocks until processed by the server.
	<-eng.data.reply        // blocks until processing is finished.
	input := eng.data.input // User input has been refreshed.
	state := eng.data.state // Engine state has been refreshed.
	dts := dt.Seconds()     // delta time as float.

	// Run physics on all the bodies; adjusting location and orientation.
	eng.bods = eng.bods[:0] // reset keeping capacity.
	for _, bod := range eng.solids {
		eng.bods = append(eng.bods, bod)
	}
	eng.physics.Step(eng.bods, dts)

	// Have the application adjust any or all state before rendering.
	input.Dt = dts                // how long to get back to here.
	input.Ut = ut                 // update ticks.
	app.Update(eng, input, state) // application to updates its own state.

	// update assets that the application changed or which need
	// per tick processing. Per-ticks include animated models,
	// particle effects, surfaces, phrases, ...
	if eng.alive {
		eng.updateModels(dts)                // load and bind updated data.
		eng.placeModels(eng.root(), lin.M4I) // update all transforms.
		eng.updateSoundListener()            // reposition sound listener.
	}
}
开发者ID:skyview059,项目名称:vu,代码行数:33,代码来源:eng.go

示例14: UpdateExpiresAtOnContainer

func (db *SQLDB) UpdateExpiresAtOnContainer(handle string, ttl time.Duration) error {
	tx, err := db.conn.Begin()
	if err != nil {
		return err
	}

	defer tx.Rollback()

	interval := fmt.Sprintf("%d second", int(ttl.Seconds()))

	_, err = tx.Exec(`
		UPDATE containers SET expires_at = NOW() + $2::INTERVAL, ttl = $3
		WHERE handle = $1
		`,
		handle,
		interval,
		ttl,
	)

	if err != nil {
		return err
	}

	return tx.Commit()
}
开发者ID:xoebus,项目名称:checkin,代码行数:25,代码来源:sqldb_containers.go

示例15: pingPeer

func pingPeer(ctx context.Context, n *core.IpfsNode, pid peer.ID, numPings int) <-chan interface{} {
	outChan := make(chan interface{})
	go func() {
		defer close(outChan)

		if len(n.Peerstore.Addrs(pid)) == 0 {
			// Make sure we can find the node in question
			outChan <- &PingResult{
				Text: fmt.Sprintf("Looking up peer %s", pid.Pretty()),
			}

			ctx, cancel := context.WithTimeout(ctx, kPingTimeout)
			defer cancel()
			p, err := n.Routing.FindPeer(ctx, pid)
			if err != nil {
				outChan <- &PingResult{Text: fmt.Sprintf("Peer lookup error: %s", err)}
				return
			}
			n.Peerstore.AddAddrs(p.ID, p.Addrs, peer.TempAddrTTL)
		}

		outChan <- &PingResult{Text: fmt.Sprintf("PING %s.", pid.Pretty())}

		ctx, cancel := context.WithTimeout(ctx, kPingTimeout*time.Duration(numPings))
		defer cancel()
		pings, err := n.Ping.Ping(ctx, pid)
		if err != nil {
			log.Debugf("Ping error: %s", err)
			outChan <- &PingResult{Text: fmt.Sprintf("Ping error: %s", err)}
			return
		}

		var done bool
		var total time.Duration
		for i := 0; i < numPings && !done; i++ {
			select {
			case <-ctx.Done():
				done = true
				break
			case t, ok := <-pings:
				if !ok {
					done = true
					break
				}

				outChan <- &PingResult{
					Success: true,
					Time:    t,
				}
				total += t
				time.Sleep(time.Second)
			}
		}
		averagems := total.Seconds() * 1000 / float64(numPings)
		outChan <- &PingResult{
			Text: fmt.Sprintf("Average latency: %.2fms", averagems),
		}
	}()
	return outChan
}
开发者ID:eminence,项目名称:go-ipfs,代码行数:60,代码来源:ping.go


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