本文整理汇总了Golang中Time.Since函数的典型用法代码示例。如果您正苦于以下问题:Golang Since函数的具体用法?Golang Since怎么用?Golang Since使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Since函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: IndexNear
// IndexNear returns the index of the blob created closed to time t. The actual
// blob ref can be retrieved by passing the index to RefAt.
func (ti *TimeIndex) IndexNear(t time.Time) int {
ti.lock.RLock()
defer ti.lock.RUnlock()
down, up := 0, len(ti.entries)-1
if up < 0 {
return -1
}
pivot, done := split(down, up)
for !done {
pivt := ti.entries[pivot].tm
if t.After(pivt) {
down, up = pivot, up
} else {
down, up = down, pivot
}
pivot, done = split(down, up)
}
lowt := ti.entries[down].tm
upt := ti.entries[up].tm
lowdiff := int64(time.Since(lowt)) - int64(time.Since(t))
updiff := int64(time.Since(t)) - int64(time.Since(upt))
if updiff < lowdiff {
return up
}
return down
}
示例2: ClientTask
func ClientTask(pipe chan<- bool) {
client, _ := zmq.NewSocket(zmq.DEALER)
client.Connect("tcp://localhost:5555")
fmt.Println("Setting up test...")
time.Sleep(100 * time.Millisecond)
fmt.Println("Synchronous round-trip test...")
start := time.Now()
var requests int
for requests = 0; requests < 10000; requests++ {
client.Send("hello", 0)
client.Recv(0)
}
fmt.Println(requests, "calls in", time.Since(start))
fmt.Println("Asynchronous round-trip test...")
start = time.Now()
for requests = 0; requests < 100000; requests++ {
client.Send("hello", 0)
}
for requests = 0; requests < 100000; requests++ {
client.Recv(0)
}
fmt.Println(requests, "calls in", time.Since(start))
pipe <- true
}
示例3: migRollingUpdatePoll
// migRollingUpdatePoll (CKE/GKE-only) polls the progress of the MIG rolling
// update with ID id until it is complete. It returns an error if this takes
// longer than nt times the number of nodes.
func migRollingUpdatePoll(id string, nt time.Duration) error {
// Two keys and a val.
status, progress, done := "status", "statusMessage", "ROLLED_OUT"
start, timeout := time.Now(), nt*time.Duration(testContext.CloudConfig.NumNodes)
var errLast error
Logf("Waiting up to %v for MIG rolling update to complete.", timeout)
// TODO(mbforbes): Refactor this to use cluster_upgrade.go:retryCmd(...)
if wait.Poll(restartPoll, timeout, func() (bool, error) {
o, err := exec.Command("gcloud", "preview", "rolling-updates",
fmt.Sprintf("--project=%s", testContext.CloudConfig.ProjectID),
fmt.Sprintf("--zone=%s", testContext.CloudConfig.Zone),
"describe",
id).CombinedOutput()
if err != nil {
errLast = fmt.Errorf("Error calling rolling-updates describe %s: %v", id, err)
Logf("%v", errLast)
return false, nil
}
output := string(o)
// The 'describe' call probably succeeded; parse the output and try to
// find the line that looks like "status: <status>" and see whether it's
// done.
Logf("Waiting for MIG rolling update: %s (%v elapsed)",
parseKVLines(output, progress), time.Since(start))
if st := parseKVLines(output, status); st == done {
return true, nil
}
return false, nil
}) != nil {
return fmt.Errorf("timeout waiting %v for MIG rolling update to complete. Last error: %v", timeout, errLast)
}
Logf("MIG rolling update complete after %v", time.Since(start))
return nil
}
示例4: run
func (cw *streamWriter) run() {
var msgc chan raftpb.Message
var heartbeatc <-chan time.Time
var t streamType
var enc encoder
var flusher http.Flusher
tickc := time.Tick(ConnReadTimeout / 3)
for {
select {
case <-heartbeatc:
start := time.Now()
if err := enc.encode(linkHeartbeatMessage); err != nil {
reportSentFailure(string(t), linkHeartbeatMessage)
cw.status.deactivate(failureType{source: t.String(), action: "heartbeat"}, err.Error())
cw.close()
heartbeatc, msgc = nil, nil
continue
}
flusher.Flush()
reportSentDuration(string(t), linkHeartbeatMessage, time.Since(start))
case m := <-msgc:
start := time.Now()
if err := enc.encode(m); err != nil {
reportSentFailure(string(t), m)
cw.status.deactivate(failureType{source: t.String(), action: "write"}, err.Error())
cw.close()
heartbeatc, msgc = nil, nil
cw.r.ReportUnreachable(m.To)
continue
}
flusher.Flush()
reportSentDuration(string(t), m, time.Since(start))
case conn := <-cw.connc:
cw.close()
t = conn.t
switch conn.t {
case streamTypeMsgAppV2:
enc = newMsgAppV2Encoder(conn.Writer, cw.fs)
case streamTypeMessage:
enc = &messageEncoder{w: conn.Writer}
default:
plog.Panicf("unhandled stream type %s", conn.t)
}
flusher = conn.Flusher
cw.mu.Lock()
cw.status.activate()
cw.closer = conn.Closer
cw.working = true
cw.mu.Unlock()
heartbeatc, msgc = tickc, cw.msgc
case <-cw.stopc:
cw.close()
close(cw.done)
return
}
}
}
示例5: Run
func (t *Tsdb) Run() {
for i := 0; i < t.Concurrency; i++ {
go t.sendData()
}
ticker := time.NewTicker(time.Second)
last := time.Now()
for {
select {
case <-ticker.C:
if time.Since(last) >= time.Second {
log.Debug("no flushes in last 1second. Flushing now.")
last = time.Now()
t.Flush()
log.Debug("flush took %f seconds", time.Since(last).Seconds())
}
case <-t.flushMetrics:
log.Debug("flush trigger received.")
last = time.Now()
t.Flush()
log.Debug("flush took %f seconds", time.Since(last).Seconds())
case <-t.flushEvents:
t.SendEvents()
case <-t.closeChan:
close(t.dataChan)
return
}
}
}
示例6: singleping
func singleping(ip string) (time.Duration, error) {
addr := net.IPAddr{IP: net.ParseIP(ip)}
sendid := os.Getpid() & 0xffff
sendseq := 1
pingpktlen := 64
sendpkt := makePingRequest(sendid, sendseq, pingpktlen, []byte("Go Ping"))
ipconn, err := net.DialIP("ip4:icmp", nil, &addr) // *IPConn (Conn 인터페이스 구현)
if err != nil {
log.Fatalf(`net.DialIP("ip4:icmp", %v) = %v`, ipconn, err)
}
ipconn.SetDeadline(time.Now().Add(time.Second)) //1 Second timeout
start := time.Now()
n, err := ipconn.WriteToIP(sendpkt, &addr)
if err != nil || n != pingpktlen {
log.Fatalf(`net.WriteToIP(..., %v) = %v, %v`, addr, n, err)
}
resp := make([]byte, 1024)
_, _, pingerr := ipconn.ReadFrom(resp)
if pingerr != nil {
fmt.Printf("%s : FAIL\n", ip)
} else {
fmt.Printf("%s : %s\n", ip, time.Since(start))
}
// log.Printf("%x", resp)
return time.Since(start), pingerr
}
示例7: Munge
// Munge is the workhorse that will actually close the PRs
func (CloseStalePR) Munge(obj *github.MungeObject) {
if !obj.IsPR() {
return
}
if obj.HasLabel(keepOpenLabel) {
return
}
lastModif, err := findLastModificationTime(obj)
if err != nil {
glog.Errorf("Failed to find last modification: %v", err)
return
}
closeIn := -time.Since(lastModif.Add(stalePullRequest))
inactiveFor := time.Since(*lastModif)
if closeIn <= 0 {
closePullRequest(obj, inactiveFor)
} else if closeIn <= startWarning {
checkAndWarn(obj, inactiveFor, closeIn)
} else {
// Pull-request is active. Remove previous potential warning
// Ignore potential errors, we just want to remove old comments ...
comment, _ := findLatestWarningComment(obj)
if comment != nil {
obj.DeleteComment(comment)
}
}
}
示例8: save
func (s *Snapshotter) save(snapshot *raftpb.Snapshot) error {
start := time.Now()
fname := fmt.Sprintf("%016x-%016x%s", snapshot.Metadata.Term, snapshot.Metadata.Index, snapSuffix)
b := pbutil.MustMarshal(snapshot)
crc := crc32.Update(0, crcTable, b)
snap := snappb.Snapshot{Crc: crc, Data: b}
d, err := snap.Marshal()
if err != nil {
return err
} else {
marshallingDurations.Observe(float64(time.Since(start)) / float64(time.Second))
}
err = pioutil.WriteAndSyncFile(path.Join(s.dir, fname), d, 0666)
if err == nil {
saveDurations.Observe(float64(time.Since(start)) / float64(time.Second))
} else {
err1 := os.Remove(path.Join(s.dir, fname))
if err1 != nil {
plog.Errorf("failed to remove broken snapshot file %s", path.Join(s.dir, fname))
}
}
return err
}
示例9: WaitForStateChange
// WaitForStateChange blocks until the state changes to something other than the sourceState
// or timeout fires. It returns false if timeout fires and true otherwise.
// TODO(zhaoq): Rewrite for complex Picker.
func (cc *Conn) WaitForStateChange(timeout time.Duration, sourceState ConnectivityState) bool {
start := time.Now()
cc.mu.Lock()
defer cc.mu.Unlock()
if sourceState != cc.state {
return true
}
expired := timeout <= time.Since(start)
if expired {
return false
}
done := make(chan struct{})
go func() {
select {
case <-time.After(timeout - time.Since(start)):
cc.mu.Lock()
expired = true
cc.stateCV.Broadcast()
cc.mu.Unlock()
case <-done:
}
}()
defer close(done)
for sourceState == cc.state {
cc.stateCV.Wait()
if expired {
return false
}
}
return true
}
示例10: read
func read(dbPath string, mapPop bool) {
opt := &bolt.Options{Timeout: 5 * time.Minute, ReadOnly: true}
if mapPop {
fmt.Println("read with MAP_POPULATE flag...")
opt = &bolt.Options{Timeout: 5 * time.Minute, ReadOnly: true, MmapFlags: syscall.MAP_POPULATE}
} else {
fmt.Println("read without MAP_POPULATE flag...")
}
to := time.Now()
db, err := bolt.Open(dbPath, 0600, opt)
if err != nil {
panic(err)
}
defer db.Close()
fmt.Println("bolt.Open took", time.Since(to))
tr := time.Now()
tx, err := db.Begin(writable)
if err != nil {
panic(err)
}
defer tx.Rollback()
bk := tx.Bucket([]byte(bucketName))
c := bk.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
// fmt.Printf("%s ---> %s.\n", k, v)
_ = k
_ = v
}
fmt.Println("bolt read took:", time.Since(tr))
}
示例11: client_task
func client_task(c chan string) {
context, _ := zmq.NewContext()
client, _ := context.NewSocket(zmq.DEALER)
defer context.Close()
defer client.Close()
client.SetIdentity("C")
client.Connect("tcp://localhost:5555")
fmt.Println("Setting up test...")
time.Sleep(time.Duration(100) * time.Millisecond)
fmt.Println("Synchronous round-trip test...")
start := time.Now()
requests := 10000
for i := 0; i < requests; i++ {
client.Send([]byte("hello"), 0)
client.Recv(0)
}
fmt.Printf("%d calls/second\n", int64(float64(requests)/time.Since(start).Seconds()))
fmt.Println("Asynchronous round-trip test...")
start = time.Now()
for i := 0; i < requests; i++ {
client.Send([]byte("hello"), 0)
}
for i := 0; i < requests; i++ {
client.Recv(0)
}
fmt.Printf("%d calls/second\n", int64(float64(requests)/time.Since(start).Seconds()))
c <- "done"
}
示例12: Clear
func (cache *Cache) Clear() {
for key, entry := range cache.datamap {
if entry.granted == true {
dur := time.Since(entry.leaseTime)
if dur > entry.leaseDur {
entry.granted = false
}
}
elem := entry.query.Front()
for elem != nil {
tempdur := time.Since(elem.Value.(time.Time))
if tempdur > time.Duration(storagerpc.QueryCacheSeconds)*time.Second {
_ = entry.query.Remove(elem)
elem = entry.query.Front()
} else {
break
}
}
if entry.query.Len() == 0 {
delete(cache.datamap, key)
}
}
}
示例13: TestMain
func TestMain(m *testing.M) {
size = numXi(index)
pk = []byte{1}
runtime.GOMAXPROCS(runtime.NumCPU())
id := flag.Int("index", 1, "graph index")
flag.Parse()
index = int64(*id)
graphDir = fmt.Sprintf("%s%d", graphDir, *id)
//os.RemoveAll(graphDir)
now := time.Now()
prover = NewProver(pk, index, name, graphDir)
fmt.Printf("%d. Graph gen: %fs\n", index, time.Since(now).Seconds())
now = time.Now()
commit := prover.Init()
fmt.Printf("%d. Graph commit: %fs\n", index, time.Since(now).Seconds())
root := commit.Commit
verifier = NewVerifier(pk, index, beta, root)
os.Exit(m.Run())
}
示例14: DispatchSync
// DispatchSync sends a body to the destination, and blocks waiting on a response.
func (rpc *AmqpRPCCLient) DispatchSync(method string, body []byte) (response []byte, err error) {
rpc.stats.Inc(fmt.Sprintf("RPC.Rate.%s", method), 1, 1.0)
rpc.stats.Inc("RPC.Traffic", int64(len(body)), 1.0)
rpc.stats.GaugeDelta("RPC.CallsWaiting", 1, 1.0)
defer rpc.stats.GaugeDelta("RPC.CallsWaiting", -1, 1.0)
callStarted := time.Now()
select {
case jsonResponse := <-rpc.Dispatch(method, body):
var rpcResponse RPCResponse
err = json.Unmarshal(jsonResponse, &rpcResponse)
if err != nil {
return
}
err = unwrapError(rpcResponse.Error)
if err != nil {
rpc.stats.Inc(fmt.Sprintf("RPC.Latency.%s.Error", method), 1, 1.0)
return
}
rpc.stats.Inc("RPC.Rate.Success", 1, 1.0)
rpc.stats.TimingDuration(fmt.Sprintf("RPC.Latency.%s.Success", method), time.Since(callStarted), 1.0)
response = rpcResponse.ReturnVal
return
case <-time.After(rpc.timeout):
rpc.stats.TimingDuration(fmt.Sprintf("RPC.Latency.%s.Timeout", method), time.Since(callStarted), 1.0)
rpc.stats.Inc("RPC.Rate.Timeouts", 1, 1.0)
rpc.log.Warning(fmt.Sprintf(" [c!][%s] AMQP-RPC timeout [%s]", rpc.clientQueue, method))
err = errors.New("AMQP-RPC timeout")
return
}
}
示例15: Gesture
// Gesture is called by the system when the LED matrix receives any kind of gesture
// it only seems to receive tap gestures ("GestureNone" type)
func (p *DemoPane) Gesture(gesture *gestic.GestureMessage) {
log.Infof("gesture received - %v, %v", gesture.Touch, gesture.Position)
// check the second last touch location since the most recent one before a tap is usually blank it seems
lastLocation := p.lastTapLocation
p.lastTapLocation = gesture.Touch
if gesture.Tap.Active() && time.Since(p.lastTap) > tapInterval {
p.lastTap = time.Now()
log.Infof("Tap! %v", lastLocation)
// change between images - right or left
if lastLocation.East {
p.imageIndex++
p.imageIndex %= len(stateImageNames)
} else {
p.imageIndex--
if p.imageIndex < 0 {
p.imageIndex = len(stateImageNames) - 1
}
}
log.Infof("Showing image: %v", stateImageNames[p.imageIndex])
}
if gesture.DoubleTap.Active() && time.Since(p.lastDoubleTap) > tapInterval {
p.lastDoubleTap = time.Now()
log.Infof("Double Tap!")
// change between image and text displaying (in Render)
p.isImageMode = !p.isImageMode
}
}