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


Golang bytefmt.ByteSize函数代码示例

本文整理汇总了Golang中github.com/pivotal-golang/bytefmt.ByteSize函数的典型用法代码示例。如果您正苦于以下问题:Golang ByteSize函数的具体用法?Golang ByteSize怎么用?Golang ByteSize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: Generate

func (m Memory) Generate() ([]i3.Output, error) {
	mem, err := mem.VirtualMemory()
	if err != nil {
		return nil, err
	}

	total := mem.Total
	used := total - mem.Buffers - mem.Cached - mem.Free

	percUsed := (100 * used) / total

	var color string
	switch {
	case m.IsCrit(int(percUsed)):
		color = i3.DefaultColors.Crit
	case m.IsWarn(int(percUsed)):
		color = i3.DefaultColors.Warn
	default:
		color = i3.DefaultColors.OK
	}

	out := make([]i3.Output, 1)
	out[0] = i3.Output{
		Name:      m.Name,
		FullText:  fmt.Sprintf(FormatString, percUsed, bytefmt.ByteSize(used), bytefmt.ByteSize(total)),
		Color:     color,
		Separator: true,
	}

	return out, nil
}
开发者ID:codekoala,项目名称:goi3bar,代码行数:31,代码来源:mem.go

示例2: AdjustMemory

func (t *TerminalUI) AdjustMemory(stats Statistics) {
	// memory gauges
	mem := make([]*ui.Gauge, len(stats.Instances))
	for i, idx := range stats.Instances {
		// show max 8 instances
		if i > 7 {
			break
		}

		memory := uint64(stats.Data[idx].Stats.Usage.Memory)
		quota := uint64(stats.Data[idx].Stats.MemoryQuota)
		percent := int(math.Ceil((float64(memory) / float64(quota)) * 100.0))
		mem[i] = ui.NewGauge()
		mem[i].Percent = percent
		mem[i].Height = 13 - min(len(stats.Instances), 8)
		mem[i].Border.Label = fmt.Sprintf("Memory - Instance %d: %d%% (%s / %s)",
			i, percent, bytefmt.ByteSize(memory), bytefmt.ByteSize(quota))
		mem[i].Border.FgColor = ui.ColorWhite
		mem[i].Border.LabelFgColor = ui.ColorWhite
		mem[i].BarColor = colors[i%6]
		mem[i].PercentColor = ui.ColorWhite
	}
	t.Memory = mem

	// update layout
	ui.Body.Rows = []*ui.Row{
		ui.NewRow(
			ui.NewCol(3, 0, t.Usage),
			ui.NewCol(3, 0, t.Summary),
			ui.NewCol(6, 0, t.Disk)),
		ui.NewRow(
			ui.NewCol(6, 0, t.CPU),
			t.newMemCol(6, 0, t.Memory)),
	}
}
开发者ID:swisscom,项目名称:cf-statistics-plugin,代码行数:35,代码来源:terminal.go

示例3: DiskUsage

func DiskUsage(path string) (disk DiskStatus) {
	fs := syscall.Statfs_t{}
	err := syscall.Statfs(path, &fs)
	if err != nil {
		return
	}
	fmt.Print("",
		"Type:", fs.Type, "\n", /* Type of filesystem (see below) */
		"Bsize:", fs.Bsize, "\n", /* Optimal transfer block size */
		"Blocks:", fs.Blocks, "\n", /* Total data blocks in filesystem */
		"Bfree:", fs.Bfree, "\n", /* Free blocks in filesystem */
		"Bavail:", fs.Bavail, "\n", /* Free blocks available to unprivileged user*/
		"Files:", fs.Files, "\n", /* Total file nodes in filesystem */
		"Ffree:", fs.Ffree, "\n", /* Free file nodes in filesystem */
		//"Fsid:", fs.Bsize, "\n",/* Filesystem ID */
		"Namelen:", fs.Namelen, "\n", /* Maximum length of filenames */
		"Frsize:", fs.Frsize, "\n", /* Fragment size (since Linux 2.6) */
		"Flags:", fs.Flags, "\n", /* Mount flags of filesystem (since Linux 2.6.36) */
		//"Spare:", fs.Bsize, "\n", /* Padding bytes reserved for future use */
	)

	disk.All = fs.Blocks * uint64(fs.Bsize)
	disk.Free = fs.Bfree * uint64(fs.Bsize)
	disk.Used = disk.All - disk.Free
	fmt.Println("",
		"Total:", disk.All, bytefmt.ByteSize(disk.All), "\n",
		"Used:", disk.Used, bytefmt.ByteSize(disk.Used), "\n",
		"Free:", disk.Free, bytefmt.ByteSize(disk.Free))
	return
}
开发者ID:michalliu,项目名称:syncthing-wrapper,代码行数:30,代码来源:spaceStatus.go

示例4: AdjustSummary

func (t *TerminalUI) AdjustSummary(stats Statistics) {
	var uptime int64
	var cpuUsage float64
	var memUsage, memQuota, diskUsage, diskQuota int64
	for _, idx := range stats.Instances {
		uptime = max(uptime, stats.Data[idx].Stats.Uptime)
		cpuUsage += stats.Data[idx].Stats.Usage.CPU
		memUsage += stats.Data[idx].Stats.Usage.Memory
		diskUsage += stats.Data[idx].Stats.Usage.Disk
		memQuota += stats.Data[idx].Stats.MemoryQuota
		diskQuota += stats.Data[idx].Stats.DiskQuota
	}
	up, _ := time.ParseDuration(fmt.Sprintf("%ds", uptime))

	summaryText := fmt.Sprintf(
		`Instances running: %d

Uptime: %s
Up Since: %s

Total CPU Usage: %.4f%%
Total Memory Usage: %s / %s
Total Disk Usage: %s / %s`,
		len(stats.Instances),
		up.String(),
		time.Now().Add(-1*up).Format("Mon, 02 Jan 2006 15:04 MST"),
		cpuUsage*100.0,
		bytefmt.ByteSize(uint64(memUsage)), bytefmt.ByteSize(uint64(memQuota)),
		bytefmt.ByteSize(uint64(diskUsage)), bytefmt.ByteSize(uint64(diskQuota)))
	t.Summary.Text = summaryText
}
开发者ID:swisscom,项目名称:cf-statistics-plugin,代码行数:31,代码来源:terminal.go

示例5: PCInitDynamic

//Initalisiert Dynamischen Pc
func (y *PCDynamic) PCInitDynamic(s *SSH) error {
	/*
		Id int						`id`

		MemFree string				`memfree`
		MemAvailable string			`memavail`
		MemUsed uint64				`memused`
		MemUsedProzent float64		`memusedprozent`

		LoadAvg float64				`loadavg`
		NumProcess uint64			`numprocess`
	*/
	loadavg := &linuxproc.LoadAvg{}
	meminfo := &linuxproc.MemInfo{}
	err := errors.New("")

	if s.Client == nil {
		err := errors.New("Could not find a ssh Client ")
		revel.ERROR.Print(err)
		return err
	} else {
		s.Download("/proc/loadavg", tempDir+"/loadavg"+strconv.Itoa(y.Id))
		loadavg, err = linuxproc.ReadLoadAvg("/proc/loadavg")
		if err != nil {
			revel.ERROR.Print(err)
			return err
		}

		y.LoadAvg = loadavg.Last1Min
		y.NumProcess = loadavg.ProcessRunning

		s.Download("/proc/meminfo", tempDir+"/meminfo"+strconv.Itoa(y.Id))
		meminfo, err = linuxproc.ReadMemInfo("/home/pr0gramming/Dokumente/meminfo" + strconv.Itoa(y.Id))
		if err != nil {
			revel.ERROR.Print(err)
			return err
		}

	}

	y.MemUsed = bytefmt.ByteSize((meminfo.MemTotal - meminfo.MemFree) * 1024)
	y.MemFree = bytefmt.ByteSize(meminfo.MemFree * 1024)
	y.MemAvailable = bytefmt.ByteSize(meminfo.MemAvailable * 1024)

	a := float64(meminfo.MemTotal)
	b := float64(meminfo.MemFree)
	y.MemUsedProzent = strconv.FormatFloat(float64(((a-b)/a)*100), 'f', -1, 64)

	//println("test: " + (y.MemUsedProzent))
	return nil
}
开发者ID:FloydZ,项目名称:xengo,代码行数:52,代码来源:pc.go

示例6: Status

func (me *CoreService) Status() *Sac {

	out := NewSac()

	m := runtime.MemStats{}
	runtime.ReadMemStats(&m)

	mem := NewSac()

	mem_gen := NewSac().
		Set("alloc", bytefmt.ByteSize(m.Alloc)).
		Set("total_alloc", bytefmt.ByteSize(m.TotalAlloc))
	mem.Set("general", mem_gen)

	mem_hp := NewSac().
		Set("alloc", bytefmt.ByteSize(m.HeapAlloc)).
		Set("sys", bytefmt.ByteSize(m.HeapAlloc)).
		Set("idle", bytefmt.ByteSize(m.HeapIdle)).
		Set("inuse", bytefmt.ByteSize(m.HeapInuse)).
		Set("released", bytefmt.ByteSize(m.HeapReleased)).
		Set("objects", bytefmt.ByteSize(m.HeapObjects))
	mem.Set("heap", mem_hp)

	out.Set("mem", mem).
		Set("server-time", time.Now().Format("2006-01-02 15:04:05 MST")).
		Set("go-version", runtime.Version()[2:]).
		Set("aqua-version", release)

	return out
}
开发者ID:tolexo,项目名称:aqua,代码行数:30,代码来源:core_service.go

示例7: Generate

func (g DiskUsageGenerator) Generate() ([]i3.Output, error) {
	items := make([]i3.Output, len(g.Items))

	for i, item := range g.Items {
		usage, err := getUsage(item.Path)
		if err != nil {
			return nil, err
		}

		free := bytefmt.ByteSize(usage.Free * bytefmt.BYTE)

		items[i].FullText = fmt.Sprintf(freeFormat, item.Name, free)

		freePercent := 100 - int(usage.UsedPerc)

		var color string
		switch {
		case freePercent < g.CritThreshold:
			color = i3.DefaultColors.Crit
		case freePercent < g.WarnThreshold:
			color = i3.DefaultColors.Warn
		default:
			color = i3.DefaultColors.OK
		}

		items[i].Color = color

		items[i].Name = g.Name
		items[i].Instance = item.Path
	}

	items[len(items)-1].Separator = true

	return items, nil
}
开发者ID:denbeigh2000,项目名称:goi3bar,代码行数:35,代码来源:disk.go

示例8: listDroplets

func (factory *DropletRunnerCommandFactory) listDroplets(context *cli.Context) {
	if !factory.ensureBlobStoreVerified() {
		return
	}

	droplets, err := factory.dropletRunner.ListDroplets()
	if err != nil {
		factory.UI.SayLine(fmt.Sprintf("Error listing droplets: %s", err))
		factory.ExitHandler.Exit(exit_codes.CommandFailed)
		return
	}

	sort.Sort(dropletSliceSortedByCreated(droplets))

	w := &tabwriter.Writer{}
	w.Init(factory.UI, 12, 8, 1, '\t', 0)

	fmt.Fprintln(w, "Droplet\tCreated At\tSize")
	for _, droplet := range droplets {
		size := bytefmt.ByteSize(uint64(droplet.Size))
		if !droplet.Created.IsZero() {
			fmt.Fprintf(w, "%s\t%s\t%s\n", droplet.Name, droplet.Created.Format("01/02 15:04:05.00"), size)
		} else {
			fmt.Fprintf(w, "%s\t\t%s\n", droplet.Name, size)
		}
	}

	w.Flush()
}
开发者ID:cloudfoundry-incubator,项目名称:ltc,代码行数:29,代码来源:droplet_runner_command_factory.go

示例9: downloadBuildpacks

func (runner *Runner) downloadBuildpacks() error {
	// Do we have a custom buildpack?
	for _, buildpackName := range runner.config.BuildpackOrder() {
		buildpackUrl, err := url.Parse(buildpackName)
		if err != nil {
			return fmt.Errorf("Invalid buildpack url (%s): %s", buildpackName, err.Error())
		}
		if !buildpackUrl.IsAbs() {
			continue
		}

		destination := runner.config.BuildpackPath(buildpackName)

		if IsZipFile(buildpackUrl.Path) {
			var size uint64
			zipDownloader := NewZipDownloader(runner.config.SkipCertVerify())
			size, err = zipDownloader.DownloadAndExtract(buildpackUrl, destination)
			if err == nil {
				fmt.Printf("Downloaded buildpack `%s` (%s)", buildpackUrl.String(), bytefmt.ByteSize(size))
			}
		} else {
			err = GitClone(*buildpackUrl, destination)
		}
		if err != nil {
			return err
		}
	}

	return nil
}
开发者ID:davidwadden,项目名称:lattice-release,代码行数:30,代码来源:runner.go

示例10: main

func main() {
	flag.Parse()
	log.Print("scanning")
	start := time.Now()
	frontend := hath.NewFrontend(dir)
	files := make(chan hath.File)
	progress := make(chan hath.Progress)
	wg := new(sync.WaitGroup)
	wg.Add(1)
	go func() {
		for p := range progress {
			log.Println("scan progress", p)
		}
	}()
	go func() {
		defer close(files)
		defer wg.Done()
		if err := frontend.Scan(files, progress); err != nil {
			log.Println("error while scanning:", err)
		} else {
			log.Println("scanned")
		}
	}()
	w := new(walker)
	for f := range files {
		// fmt.Print(".")
		w.count++
		w.sum += f.Size
	}
	wg.Wait()
	log.Println("end")
	end := time.Now()
	duration := end.Sub(start)
	log.Println("count", w.count, "size", bytefmt.ByteSize(uint64(w.sum)), "duration", duration)
}
开发者ID:RyuaNerin,项目名称:hath,代码行数:35,代码来源:main.go

示例11: Fetch

func Fetch(url string) (*ServerInfo, error) {
	if url == "" {
		return nil, fmt.Errorf("Error fetching server info: url can not be empty.")
	}
	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	v := &struct {
		MemStats runtime.MemStats `"json":"memstats"`
	}{}
	if err := json.NewDecoder(resp.Body).Decode(v); err != nil {
		log.Fatalln(err.Error())
	}

	p := time.Duration(v.MemStats.PauseTotalNs) * time.Nanosecond
	return &ServerInfo{
		GC: GC{
			CPUFraction:   v.MemStats.GCCPUFraction,
			Num:           v.MemStats.NumGC,
			PauseTotal:    p,
			PauseTotalStr: p.String(),
			Enabled:       v.MemStats.EnableGC,
			Debug:         v.MemStats.DebugGC,
		},
		Mem: Mem{
			TotalAlloc:    v.MemStats.TotalAlloc,
			TotalAllocStr: bytefmt.ByteSize(v.MemStats.TotalAlloc),
		},
	}, nil
}
开发者ID:danielfireman,项目名称:phd,代码行数:31,代码来源:serverinfo.go

示例12: main

func main() {

	argsWithoutProg := os.Args[1:]

	if len(argsWithoutProg) == 0 {
		fmt.Println("Usage: go run sum.go filter")
		return
	}
	filter := strings.Join(argsWithoutProg, " ")

	file, err := os.Open("diff.txt")
	check(err)
	defer file.Close()

	var added, removed uint64

	re, err := regexp.Compile(`(.+)\:`)

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		if len(line) > 3 && strings.Contains(line[3:], filter) {
			if line[0:3] == "Inc" || line[0:3] == "New" {
				res := re.FindStringSubmatch(line[4:])
				if len(res) > 0 {
					added += SizeInBytes(res[1])
				}
			} else if line[0:3] == "Dec" || line[0:3] == "Rem" {
				res := re.FindStringSubmatch(line[4:])
				if len(res) > 0 {
					removed += SizeInBytes(res[1])
				}
			}

		}
	}

	color.Green("Added: " + bytefmt.ByteSize(added))
	color.Yellow("Removed: " + bytefmt.ByteSize(removed))

	diff := int64(added) - int64(removed)
	if diff < 0 {
		color.Yellow("= Net total: -" + bytefmt.ByteSize(uint64(-diff)))
	} else {
		color.Green("= Net total: " + bytefmt.ByteSize(uint64(diff)))
	}
}
开发者ID:davidhq,项目名称:snapshots,代码行数:47,代码来源:sum.go

示例13: main

func main() {
	var delete = false
	flag.BoolVar(&delete, "delete", false, "Delete all JPG sidecar files.")
	flag.Parse()

	if len(flag.Args()) < 1 {
		log.Fatalf("Must supply a path to a Lightroom catalog file.")
	}
	path := flag.Args()[0]
	log.Printf("Processing %s", path)

	catalog, err := NewCatalog(path)
	if err != nil {
		log.Fatal(err)
	}

	if !delete {
		stats := catalog.GetSidecarStats()
		log.Printf("There are %d sidecar entries totalling %s bytes on disk.",
			stats.Count, bytefmt.ByteSize(uint64(stats.TotalSizeBytes)))
		return
	}

	var processed_count uint
	var error_count uint
	var skip_count uint
	var missing_count uint
	var count uint
	catalog.ProcessSidecars(func(sidecarPath string, originalPath string) error {
		if _, err := os.Stat(sidecarPath); err == nil {
			if _, err := os.Stat(originalPath); os.IsNotExist(err) {
				log.Printf("Missing original path for sidecar; Skipping %s", sidecarPath)
				skip_count++
				return nil
			}

			log.Printf("Deleting %s", sidecarPath)
			err = os.Remove(sidecarPath)
			if err != nil {
				log.Printf("Error deleting %s; %v.", sidecarPath, err)
				error_count++
				return err
			} else {
				processed_count++
			}
		} else {
			log.Printf("Missing %s", sidecarPath)
			missing_count++
		}
		count++
		return nil
	})
	log.Printf("Done.")
	log.Printf("   Total:   %d", count)
	log.Printf("   Deleted: %d", processed_count)
	log.Printf("   Skipped: %d", skip_count)
	log.Printf("   Missing: %d", missing_count)
}
开发者ID:aalpern,项目名称:lightroom-purge-sidecars,代码行数:58,代码来源:main.go

示例14: convertSize

func convertSize(s string) string {
	// aus 314572800000 wird 962.1G
	ret, err := strconv.ParseUint(s, 10, 64)
	if err != nil {
		log.Error(err.Error())
		return ""
	}
	str := bytefmt.ByteSize(ret)
	log.Info("Aus " + s + " wurde " + str)
	return str
}
开发者ID:FloydZ,项目名称:hddgo,代码行数:11,代码来源:harddrive.go

示例15: watchGrabber

func watchGrabber(g grabber.Grabberer) {
	tick := time.NewTicker(3 * time.Second)
	defer tick.Stop()
	for {
		select {
		case <-tick.C:
			log.Printf("Downloading at %v", bytefmt.ByteSize(uint64(g.Strategy().DownloadRate())))
		case <-g.PostProcessable():
			return
		}
	}
}
开发者ID:frank3nst3in,项目名称:grabby,代码行数:12,代码来源:grabby.go


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