本文整理匯總了Golang中fmt.Printf函數的典型用法代碼示例。如果您正苦於以下問題:Golang Printf函數的具體用法?Golang Printf怎麽用?Golang Printf使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Printf函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: processAmqp
// Process messages from the AMQP queues
func processAmqp(username, amqpAddress string) {
// Open the queue and then begin processing messages
// If we drop out of the processing function, wait
// a little while and try again
for {
fmt.Printf("######################################################################################################\n")
fmt.Printf("UTM-API service (%s) REST interface opening %s...\n", globals.LogTag, amqpAddress)
q, err := OpenQueue(username, amqpAddress)
if err == nil {
defer q.Close()
fmt.Printf("%s [server] --> connection opened.\n", globals.LogTag)
downlinkMessages = q.Downlink
// The meat is in here
processDatagrams(q)
} else {
globals.Dbg.PrintfTrace("%s [server] --> error opening AMQP queue (%s).\n", globals.LogTag, err.Error())
}
amqpRetryCount++
globals.Dbg.PrintfTrace("%s [server] --> waiting before trying again...\n", globals.LogTag)
time.Sleep(time.Second * 10)
}
}
示例2: handlePacket
func handlePacket(buffer []byte) {
parser := rfc5424.NewParser(buffer)
err := parser.Parse()
if err != nil {
fmt.Printf("Error reading syslog message %s", err)
return
}
log := parser.Dump()
log["@timestamp"] = log["timestamp"]
log["facility_label"] = FACILITY_LABELS[(log["facility"]).(int)]
log["severity_label"] = SEVERITY_LABELS[(log["severity"]).(int)]
log["type"] = "syslog"
now := time.Now()
index := "logstash-" + now.Format("2006.01.02")
_, err = elasticSearch.Index(true, index, "logs", "", log)
if err != nil {
fmt.Printf("Error indexing message %s", err)
return
}
fmt.Println("Logged")
}
示例3: main
func main() {
n := 0
if len(os.Args) > 1 {
n, _ = strconv.Atoi(os.Args[1])
}
minDepth := 4
maxDepth := minDepth + 2
if maxDepth < n {
maxDepth = n
}
stretchDepth := maxDepth + 1
check := create(0, stretchDepth).Check()
fmt.Printf("stretch tree of depth %d\t check: %d\n", stretchDepth, check)
longLivedTree := create(0, maxDepth)
for depth := minDepth; depth <= maxDepth; depth += 2 {
iterations := 1 << uint(maxDepth-depth+minDepth)
check = 0
for i := 1; i <= iterations; i++ {
check += create(i, depth).Check()
check += create(-i, depth).Check()
}
fmt.Printf("%d\t trees of depth %d\t check: %d\n", 2*iterations, depth, check)
}
fmt.Printf("long lived tree of depth %d\t check: %d\n", maxDepth, longLivedTree.Check())
}
示例4: TestCalibrateThreshold
func TestCalibrateThreshold(t *testing.T) {
if !*calibrate {
t.Log("not calibrating, use -calibrate to do so.")
return
}
lower := int(1e3) // math/big is faster at this size.
upper := int(300e3) // FFT is faster at this size.
big, fft := measureMul(lower)
lowerX := float64(big) / float64(fft)
fmt.Printf("speedup at size %d: %.2f\n", lower, lowerX)
big, fft = measureMul(upper)
upperX := float64(big) / float64(fft)
fmt.Printf("speedup at size %d: %.2f\n", upper, upperX)
for {
mid := (lower + upper) / 2
big, fft := measureMul(mid)
X := float64(big) / float64(fft)
fmt.Printf("speedup at size %d: %.2f\n", mid, X)
switch {
case X < 0.98:
lower = mid
lowerX = X
case X > 1.02:
upper = mid
upperX = X
default:
fmt.Printf("speedup at size %d: %.2f\n", lower, lowerX)
fmt.Printf("speedup at size %d: %.2f\n", upper, upperX)
return
}
}
}
示例5: TestChan3
func TestChan3() {
fmt.Println("@@@@@@@@@@@@ TestChan 3")
fmt.Printf("cpu num: %d\n", runtime.NumCPU()) // 8核cpu
// 雖然goroutine是並發執行的,但是它們並不是並行運行的。如果不告訴Go額外的東西,同
// 一時刻隻會有一個goroutine執行。利用runtime.GOMAXPROCS(n)可以設置goroutine
// 並行執行的數量。GOMAXPROCS 設置了同時運行的CPU 的最大數量,並返回之前的設置。
val := runtime.GOMAXPROCS(runtime.NumCPU() * 4)
fmt.Printf("last goroutine num: %d\n", val) // 8個
fmt.Printf("goroutine num: %d\n", runtime.NumGoroutine()) // 4個goroutine同時運行
var ch1 chan int = make(chan int, 0)
var ch2 chan int = make(chan int, 0)
var ch3 chan int = make(chan int, 0)
go write(ch1, 22)
go write(ch2, 33)
go write(ch3, 44)
go read(ch1)
go read(ch2)
go read(ch3)
fmt.Printf("goroutine num: %d\n", runtime.NumGoroutine()) // 10個goroutine同時運行
sleep("TestChan3", 3)
}
示例6: drawFittedTableQLetters
//line fitted_type.got:17
func drawFittedTableQLetters(rSeq, qSeq alphabet.QLetters, index alphabet.Index, table []int, a [][]int) {
tw := tabwriter.NewWriter(os.Stdout, 0, 0, 0, ' ', tabwriter.AlignRight|tabwriter.Debug)
fmt.Printf("rSeq: %s\n", rSeq)
fmt.Printf("qSeq: %s\n", qSeq)
fmt.Fprint(tw, "\tqSeq\t")
for _, l := range qSeq {
fmt.Fprintf(tw, "%c\t", l)
}
fmt.Fprintln(tw)
r, c := rSeq.Len()+1, qSeq.Len()+1
fmt.Fprint(tw, "rSeq\t")
for i := 0; i < r; i++ {
if i != 0 {
fmt.Fprintf(tw, "%c\t", rSeq[i-1].L)
}
for j := 0; j < c; j++ {
p := pointerFittedQLetters(rSeq, qSeq, i, j, table, index, a, c)
if p != "" {
fmt.Fprintf(tw, "%s % 3v\t", p, table[i*c+j])
} else {
fmt.Fprintf(tw, "%v\t", table[i*c+j])
}
}
fmt.Fprintln(tw)
}
tw.Flush()
}
示例7: urlShortenerMain
func urlShortenerMain(client *http.Client, argv []string) {
if len(argv) != 1 {
fmt.Fprintf(os.Stderr, "Usage: urlshortener http://goo.gl/xxxxx (to look up details)\n")
fmt.Fprintf(os.Stderr, " urlshortener http://example.com/long (to shorten)\n")
return
}
svc, _ := urlshortener.New(client)
urlstr := argv[0]
// short -> long
if strings.HasPrefix(urlstr, "http://goo.gl/") || strings.HasPrefix(urlstr, "https://goo.gl/") {
url, err := svc.Url.Get(urlstr).Do()
if err != nil {
log.Fatalf("URL Get: %v", err)
}
fmt.Printf("Lookup of %s: %s\n", urlstr, url.LongUrl)
return
}
// long -> short
url, err := svc.Url.Insert(&urlshortener.Url{
Kind: "urlshortener#url", // Not really needed
LongUrl: urlstr,
}).Do()
if err != nil {
log.Fatalf("URL Insert: %v", err)
}
fmt.Printf("Shortened %s => %s\n", urlstr, url.Id)
}
示例8: work
func work(c *replicant.Client, C <-chan time.Time, stop chan bool, done chan bool, dl *ygor.DataLogger) {
defer func() {
done <- true
}()
for {
select {
case <-C:
break
case <-stop:
return
}
start := time.Now()
_, err := c.Call("echo", "echo", []byte("hello world"), 0)
end := time.Now()
if err.Status == replicant.SUCCESS {
when := uint64(end.UnixNano())
data := uint64(end.Sub(start).Nanoseconds())
er := dl.Record(1, when, data)
if er != nil {
fmt.Printf("error: %s\n", er)
os.Exit(1)
}
} else {
fmt.Printf("error: %s\n", err)
os.Exit(1)
}
}
}
示例9: main
func main() {
var f float64
fmt.Printf("Enter value in Fahrenheit : ")
fmt.Scanf("%f", &f)
fmt.Printf("Value in Celcius : %f\n", ftoc.FtoC(f))
}
示例10: transfer
func transfer(dst_name string, src io.Reader) error {
config := goftp.Config{
User: username,
Password: password,
ConnectionsPerHost: 10,
Timeout: 10 * time.Second,
Logger: nil,
}
fmt.Printf("Dialing into %s... ", host)
client, err := goftp.DialConfig(config, host)
if err != nil {
return err
}
fmt.Println("done.")
fmt.Printf("Writing to file %s... ", dst_name)
err = client.Store(dst_name, src)
if err != nil {
return err
}
fmt.Println("done.")
return nil
}
示例11: quicksort
func quicksort(low, high int, buf []int) {
pivot := buf[low+(high-low)/2] // ここでは、樞軸は単に buf の中心。
l, r := low, high
fmt.Printf("start: buf = %v, pivot = %d, l(low) =, %d, r(high) = %d\n", buf, pivot, l, r)
for {
for pivot > buf[l] { // 要素 < 樞軸 ならよし。
l++
}
for pivot < buf[r] { // 樞軸 < 要素 ならよし。
r--
}
if l >= r {
fmt.Printf("for break: buf = %v, pivot = %d, l(low) =, %d, r(high) = %d\n", buf, pivot, l, r)
break // 始點と終點が交差したらループを抜ける。
}
// 條件に合致しなければ交換。
buf[l], buf[r] = buf[r], buf[l]
l++
r--
}
// l-1 と r-1 がミソっぽい。
// l-1 と r-1 を境界にして、それぞれのグループに対してさらに quicksort() する。
fmt.Printf("recurrence? buf = %v, low < l - 1 ? %v < %v - 1, high > r + 1 ? %v > %v + 1\n", buf, low, l, high, r)
if low < l-1 {
fmt.Println()
quicksort(low, l-1, buf)
}
if high > r+1 {
fmt.Println()
quicksort(r+1, high, buf)
}
}
示例12: decodeStopRecord
func decodeStopRecord() {
jsonStr := `{
"type": "flv",
"stream_event": "flv",
"ori_url": "rtmp://pushyf.hifun.mobi/live/10016593_4VZIi6Cnwxdev",
"domain":"send.a.com",
"app":"live",
"stream":"10016593_4VZIi6Cnwxdev",
"uri":"hls.a.com/live/hls_bew000/hls_bew000_20160707150625_20160707175817.m3u8",
"start_time": 1470306194,
"stop_time": 1470306497,
"duration": 275,
"size":8987799,
"cdn_url": "http://hls.a.com/live/hls_bew000/hls_bew000_20160707150625_20160707175817.m3u8"
}`
rec := YFRecCallback{}
if err := json.Unmarshal([]byte(jsonStr), &rec); err != nil {
fmt.Printf("json unmarshal err:%v\n", err)
} else {
param["liveid"] = rec.Stream
param["url"] = rec.CdnUrl
param["duration"] = strconv.Itoa(int(rec.Duration))
param["size"] = strconv.Itoa(rec.Size)
fmt.Printf("decodeStopRecord rec : %v \n%v \n", rec, param)
}
}
示例13: main
func main() {
origin := "http://localhost:8000/"
url := os.Args[1]
secret := os.Args[2]
clients, _ := strconv.Atoi(os.Args[3])
fmt.Printf("clients: %d\n", clients)
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
token := auth.GenerateClientToken(secret, "test", timestamp, "")
connectMessage := fmt.Sprintf("{\"params\": {\"timestamp\": \"%s\", \"token\": \"%s\", \"user\": \"test\"}, \"method\": \"connect\"}", timestamp, token)
subscribeMessage := "{\"params\": {\"channel\": \"test\"}, \"method\": \"subscribe\"}"
done := make(chan struct{})
for i := 0; i < clients; i += 1 {
chSub := make(chan struct{})
go subscriber(chSub, url, origin, connectMessage, subscribeMessage)
<-chSub
fmt.Printf("\r%d", i+1)
}
// Just run until interrupted keeping connections open.
<-done
}
示例14: Output
func Output(ps Profiles, c Config) {
if c.Tsv {
if !c.NoHeaders {
fmt.Printf("Count\tMin\tMax\tSum\tAvg\tP1\tP50\tP99\tStddev\tMin(Body)\tMax(Body)\tSum(Body)\tAvg(Body)\tMethod\tUri")
fmt.Println("")
}
for _, p := range ps {
fmt.Printf("%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v",
p.Cnt, Round(p.Min), Round(p.Max), Round(p.Sum), Round(p.Avg),
Round(p.P1), Round(p.P50), Round(p.P99), Round(p.Stddev),
Round(p.MinBody), Round(p.MaxBody), Round(p.SumBody), Round(p.AvgBody),
p.Method, p.Uri)
fmt.Println("")
}
} else {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Count", "Min", "Max", "Sum", "Avg",
"P1", "P50", "P99", "Stddev",
"Min(Body)", "Max(Body)", "Sum(Body)", "Avg(Body)",
"Method", "Uri"})
for _, p := range ps {
data := []string{
fmt.Sprint(p.Cnt), Round(p.Min), Round(p.Max), Round(p.Sum), Round(p.Avg),
Round(p.P1), Round(p.P50), Round(p.P99), Round(p.Stddev),
Round(p.MinBody), Round(p.MaxBody), Round(p.SumBody), Round(p.AvgBody),
p.Method, p.Uri}
table.Append(data)
}
table.Render()
}
}
示例15: main
func main() {
flag.Parse()
b, err := parseFile(fmt.Sprintf("%s/%s.txt", *dir, *month))
if err != nil {
log.Fatal(err)
}
fmt.Println("Total:", b.Total)
fmt.Println("Remaining:", b.Remaining)
mon := *month
year, err := strconv.Atoi(mon[0:4])
if err != nil {
log.Fatal(err)
}
m, err := strconv.Atoi(mon[4:6])
if err != nil {
log.Fatal(err)
}
rpd := b.Remaining / float64(daysIn(time.Month(m), year)-time.Now().Day())
fmt.Printf("Remaining/day: %.2f\n", rpd)
top := map[string]float64{}
for _, t := range b.Transactions {
top[t.Name] += t.Cost
}
fmt.Println("Top costs:")
pl := sortMapByValue(top)
for _, p := range pl {
fmt.Printf("\t%s: %.2f\n", p.Key, p.Value)
}
}