本文整理汇总了Golang中Time.Duration.Nanoseconds方法的典型用法代码示例。如果您正苦于以下问题:Golang Duration.Nanoseconds方法的具体用法?Golang Duration.Nanoseconds怎么用?Golang Duration.Nanoseconds使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Time.Duration
的用法示例。
在下文中一共展示了Duration.Nanoseconds方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Server
func Server(stop chan int) {
channel := make(chan []*big.Int, 1)
fmt.Printf("Server wird gestartet\n")
tcpAddr, err := net.ResolveTCPAddr("tcp4", ":9999")
checkError(err)
listener, err := net.ListenTCP("tcp", tcpAddr)
checkError(err)
fmt.Printf("Server wartet auf Verbindungsanfragen\n")
conn, err := listener.Accept()
if err != nil {
}
var time0 time.Time
var duration time.Duration
time0 = time.Now()
handleClient(channel, conn)
duration = time.Since(time0)
fmt.Print(float64(duration.Nanoseconds()) / 1000 / 1000)
listener.Close()
stop <- 1
}
示例2: 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()
}
示例3: TimerL
func TimerL(name string, duration time.Duration, rate float64) {
if rand.Float64() > rate {
return
}
HistogramL(name, float64(duration.Nanoseconds()/1000000), rate)
}
示例4: NewMapper
// NewMapper returns a new instance of Mapper with a given function and interval.
func NewMapper(fn MapFunc, itr Iterator, interval time.Duration) *Mapper {
return &Mapper{
fn: fn,
itr: itr,
interval: interval.Nanoseconds(),
}
}
示例5: NewPingChecker
// NewPingChecker returns a check function that can check if a host answer to a ICMP Ping
func NewPingChecker(host, service, ip string) CheckFunction {
return func() Event {
var retRtt time.Duration
var result = Event{Host: host, Service: service, State: "critical"}
p := fastping.NewPinger()
p.MaxRTT = maxPingTime
ra, err := net.ResolveIPAddr("ip4:icmp", ip)
if err != nil {
result.Description = err.Error()
}
p.AddIPAddr(ra)
p.OnRecv = func(addr *net.IPAddr, rtt time.Duration) {
result.State = "ok"
result.Metric = float32(retRtt.Nanoseconds() / 1e6)
}
err = p.Run()
if err != nil {
result.Description = err.Error()
}
return result
}
}
示例6: SendUsage
// SendUsage is called at the end of processing a request and will record info
// about the request for analytics and error detection later
func SendUsage(
c *Context,
statusCode int,
contentLength int,
dur time.Duration,
errors []string,
) {
m := Usage{}
m.Method = c.GetHTTPMethod()
m.URL = c.Request.URL.String()
// Remove querystring and replace IDs to allow grouping
endPointURL := regURLIDs.ReplaceAllString(
strings.Split(m.URL, "?")[0],
repURLIDs,
)
if strings.Contains(endPointURL, "/out/") {
endPointURL = regJumpLink.ReplaceAllString(endPointURL, repJumpLink)
}
m.EndPointURL = endPointURL
// Only send first 4 chars
if c.Auth.AccessToken.TokenValue != "" {
m.AccessToken = c.Auth.AccessToken.TokenValue[:4]
}
// Only send last two sections of IP address
if c.Request.Header.Get("X-Real-IP") != "" {
if strings.Contains(c.Request.Header.Get("X-Real-IP"), ".") {
// IPv4
m.IPAddr = strings.Join(
strings.Split(c.Request.Header.Get("X-Real-IP"), ".")[2:],
".",
)
} else if strings.Contains(c.Request.Header.Get("X-Real-IP"), ":") {
// IPv6
ipv6Split := strings.Split(c.Request.Header.Get("X-Real-IP"), ":")
m.IPAddr = strings.Join(ipv6Split[(len(ipv6Split)-2):], ":")
}
}
m.UserAgent = c.Request.UserAgent()
m.HTTPStatus = statusCode
m.Host = c.Request.Host
m.ContentLength = contentLength
m.Created = time.Now().Format(time.RFC3339)
m.TimeSpent = dur.Nanoseconds()
m.SiteID = c.Site.ID
m.UserID = c.Auth.UserID
m.ProfileID = c.Auth.ProfileID
if len(errors) > 0 {
m.Error = strings.Join(errors, ", ")
}
m.Send()
}
示例7: SendReadTimeout
// SendReadTimeout instructs the peer to simulate a read timeout. It then waits
// for acknowledgement of the timeout, buffering any packets received since
// then. The packets are then returned.
func (p *packetAdaptor) SendReadTimeout(d time.Duration) ([][]byte, error) {
payload := make([]byte, 1+8)
payload[0] = opcodeTimeout
binary.BigEndian.PutUint64(payload[1:], uint64(d.Nanoseconds()))
if _, err := p.Conn.Write(payload); err != nil {
return nil, err
}
packets := make([][]byte, 0)
for {
opcode, err := p.readOpcode()
if err != nil {
return nil, err
}
switch opcode {
case opcodeTimeoutAck:
// Done! Return the packets buffered and continue.
return packets, nil
case opcodePacket:
// Buffer the packet for the caller to process.
packet, err := p.readPacketBody()
if err != nil {
return nil, err
}
packets = append(packets, packet)
default:
return nil, fmt.Errorf("unexpected opcode '%s'", opcode)
}
}
}
示例8: UpdateExpectedDuration
// update the expected duration that we expect the given task to take when run on the
// given host
func UpdateExpectedDuration(t *task.Task, timeTaken time.Duration) error {
matcher := bson.M{
"name": t.DisplayName,
"build_variant": t.BuildVariant,
"branch": t.Project,
}
taskBk, err := findOneTaskBk(matcher, bson.M{})
if err != nil {
return err
}
var averageTaskDuration time.Duration
if taskBk == nil {
averageTaskDuration = timeTaken
} else {
averageTime := ((taskBk.ExpectedDuration.Nanoseconds() * taskBk.NumStarted) + timeTaken.Nanoseconds()) / (taskBk.NumStarted + 1)
averageTaskDuration = time.Duration(averageTime)
}
// for now, we are just using the duration of the last comparable task ran as the
// guess for upcoming tasks
update := bson.M{
"$set": bson.M{"expected_duration": averageTaskDuration},
"$inc": bson.M{"num_started": 1},
}
return upsertOneTaskBk(matcher, update)
}
示例9: work
func (t *Thread) work(id int) {
log.LogMessage(t.TAG, " thread work, id:", id)
var start_time time.Time
var delay time.Duration
warninglvl := 50 * time.Millisecond
for {
select {
case rpc := <-t.Queue[id]:
log.LogMessage(t.TAG, " thread:", id, rpc.GetSrc(), " call:", rpc.GetMethod())
start_time = time.Now()
err := rpc.Call()
if err != nil {
log.LogError("rpc error:", err)
}
delay = time.Now().Sub(start_time)
if delay > warninglvl {
log.LogWarning("rpc call ", rpc.GetMethod(), " delay:", delay.Nanoseconds()/1000000, "ms")
}
err = rpc.Done()
if err != nil {
log.LogError("rpc error:", err)
}
rpc.Free()
break
default:
if t.Quit {
log.LogMessage(t.TAG, " thread ", id, " quit")
return
}
time.Sleep(time.Millisecond)
}
}
}
示例10: segmentSize
func segmentSize(duration time.Duration) time.Duration {
var segmentSize time.Duration
for i := int64(1); i < duration.Nanoseconds(); i = i * 10 {
segmentSize = time.Duration(i)
}
return segmentSize
}
示例11: dumpReadToFile
func dumpReadToFile(results []Result) {
f, err := os.Create("results-read.txt")
check(err)
defer func() {
if err := f.Close(); err != nil {
panic(err)
}
}()
var duration time.Duration
for _, result := range results {
times := strings.Split(result.ReadTimes, ",")
durations := make([]string, len(times))
for i := 0; i < len(times); i++ {
duration, err = time.ParseDuration(times[i])
if err != nil {
fmt.Println(err)
fmt.Println("index:", i, times[i])
duration = time.Duration(0)
}
durations[i] = fmt.Sprintf("%d", duration.Nanoseconds())
}
_, err := f.WriteString(strings.Join(durations, ",") + "\n")
check(err)
}
}
示例12: QuerySince
func (g *Client) QuerySince(q string, ago time.Duration) Datapoints {
if ago.Nanoseconds() <= 0 {
return Datapoints{errors.New("Duration is expected to be positive."), "", nil}
}
// Cloning to be able to modify.
url := g.URL
url.Path = path.Join(url.Path, "/render")
queryPart := constructQueryPart([]string{q})
queryPart.Add("from", graphiteSinceString(ago))
url.RawQuery = queryPart.Encode()
resp, err := http.Get(url.String())
if err != nil {
return Datapoints{err, "", nil}
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return Datapoints{err, "", nil}
}
points, err := parseGraphiteResponse(body)
return parseSingleGraphiteResponse(points, err)
}
示例13: QueryMultiSince
// Fetches one or multiple Graphite series. Deferring identifying whether the
// result are ints of floats to later. Useful in clients that executes adhoc
// queries.
func (g *Client) QueryMultiSince(q []string, ago time.Duration) (MultiDatapoints, error) {
if ago.Nanoseconds() <= 0 {
return nil, errors.New("Duration is expected to be positive.")
}
// Cloning to be able to modify.
url := g.URL
url.Path = path.Join(url.Path, "/render")
queryPart := constructQueryPart(q)
queryPart.Add("from", graphiteSinceString(ago))
url.RawQuery = queryPart.Encode()
resp, err := g.Client.Get(url.String())
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return parseGraphiteResponse(body)
}
示例14: main
func main() {
runtime.GOMAXPROCS(numOfCore)
file, err := os.Create("app_host_list.txt")
if err != nil {
fmt.Println(err)
}
queue := make(chan *pingResult)
for i := 0; i < numOfCore; i++ {
go pingRoutine(queue, i*hostPerCore, (i+1)*hostPerCore)
}
succ := 0.0
var fastDuration *time.Duration
var fastHostname string
for i := 0; i < maxAppleHost; i++ {
result := <-queue
if result.Error == nil {
succ = succ + 1
if fastDuration == nil ||
result.Duration.Nanoseconds() < fastDuration.Nanoseconds() {
fastDuration = result.Duration
fastHostname = result.Hostname
}
file.WriteString(fmt.Sprint(result.Duration, "\t", result.Hostname, "\n"))
} else {
fmt.Println(result.Hostname, ": ", result.Error)
}
if i%100 == 0 {
fmt.Printf(". %d ", i)
}
}
fmt.Println("\nSucceeded: ", succ/maxAppleHost)
fmt.Println("Fast: ", fastHostname, " Duration: ", fastDuration)
}
示例15: newImagePolicyWebhook
// newImagePolicyWebhook creates a temporary kubeconfig file from the provided arguments and attempts to load
// a new newImagePolicyWebhook from it.
func newImagePolicyWebhook(callbackURL string, clientCert, clientKey, ca []byte, cacheTime time.Duration, defaultAllow bool) (*imagePolicyWebhook, error) {
tempfile, err := ioutil.TempFile("", "")
if err != nil {
return nil, err
}
p := tempfile.Name()
defer os.Remove(p)
config := v1.Config{
Clusters: []v1.NamedCluster{
{
Cluster: v1.Cluster{Server: callbackURL, CertificateAuthorityData: ca},
},
},
AuthInfos: []v1.NamedAuthInfo{
{
AuthInfo: v1.AuthInfo{ClientCertificateData: clientCert, ClientKeyData: clientKey},
},
},
}
if err := json.NewEncoder(tempfile).Encode(config); err != nil {
return nil, err
}
tempconfigfile, err := ioutil.TempFile("", "")
if err != nil {
return nil, err
}
pc := tempconfigfile.Name()
defer os.Remove(pc)
configTmpl, err := template.New("testconfig").Parse(defaultConfigTmplYAML)
if err != nil {
return nil, fmt.Errorf("failed to parse test template: %v", err)
}
dataConfig := struct {
KubeConfig string
AllowTTL int64
DenyTTL int64
RetryBackoff int64
DefaultAllow bool
}{
KubeConfig: p,
AllowTTL: cacheTime.Nanoseconds(),
DenyTTL: cacheTime.Nanoseconds(),
RetryBackoff: 0,
DefaultAllow: defaultAllow,
}
if err := configTmpl.Execute(tempconfigfile, dataConfig); err != nil {
return nil, fmt.Errorf("failed to execute test template: %v", err)
}
// Create a new admission controller
configFile, err := os.Open(pc)
if err != nil {
return nil, fmt.Errorf("failed to read test config: %v", err)
}
defer configFile.Close()
wh, err := NewImagePolicyWebhook(configFile)
return wh.(*imagePolicyWebhook), err
}