本文整理汇总了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)
}
}
}
示例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
}
}
示例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)
}
}
示例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
}
示例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
}
}
示例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)
}
示例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
}
示例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()
}
}()
}
}
示例9: TimerL
func TimerL(name string, duration time.Duration, rate float64) {
if rand.Float64() > rate {
return
}
HistogramL(name, float64(duration.Nanoseconds()/1000000), rate)
}
示例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()
}
示例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),
}
}
示例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
}
示例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
}
示例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
}
示例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
}