《go语言圣经》练习答案--第二章

2.6. 包和文件

练习 2.1: 向tempconv包添加类型、常量和函数用来处理Kelvin绝对温度的转换,Kelvin 绝对零度是−273.15°C,Kelvin绝对温度1K和摄氏度1°C的单位间隔是一样的。

 tempconv.go 用来存放变量的声明、对应的常量,还有方法。

package tempconv

import "fmt"

type Celsius float64    // 摄氏温度
type Fahrenheit float64 // 华氏温度
type Kelvin float64     //开尔文

const (
	AbsoluteZeroC Celsius = -273.15 // 绝对零度
	FreezingC     Celsius = 0       // 结冰点温度
	BoilingC      Celsius = 100     // 沸水温度
	AbsoluteZeroK Kelvin  = 0
	FreezingK     Kelvin  = 273.15
	BoilingK      Kelvin  = 373.15
)

func (c Celsius) String() string    { return fmt.Sprintf("%g°C", c) }
func (f Fahrenheit) String() string { return fmt.Sprintf("%g°F", f) }
func (k Kelvin) String() string     { return fmt.Sprintf("%g°K", k) }


conv.go 用来存放转换函数

package tempconv

// CToF converts a Celsius temperature to Fahrenheit.
func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }

// FToC converts a Fahrenheit temperature to Celsius.
func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }

//KToC CToK 摄氏度<->开尔文
func KToC(k Kelvin) Celsius { return Celsius(k - 273.15) }
func CToK(c Celsius) Kelvin { return Kelvin(c + 273.15) }

//KToF FToK 华氏度<->开尔文
func KToF(k Kelvin) Fahrenheit { return Fahrenheit((k-273.15)*9/5 + 32) }
func FToK(f Fahrenheit) Kelvin { return Kelvin(((f - 32) * 5 / 9) + 273.15) }

练习 2.2: 写一个通用的单位转换程序,用类似cf程序的方式从命令行读取参数,如果缺省的话则是从标准输入读取参数,然后做类似Celsius和Fahrenheit的单位转换,长度单位可以对应英尺和米,重量单位可以对应磅和公斤等。

cf 程序如下

$ go build gopl.io/ch2/cf
$ ./cf 32
32°F = 0°C, 32°C = 89.6°F
$ ./cf 212
212°F = 100°C, 212°C = 413.6°F
$ ./cf -40
-40°F = -40°C, -40°C = -40°F

我们的程序:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type Meter float64    //米
type Feet float64     //英尺
type Kilogram float64 //千克
type Pound float64    //磅

func (m Meter) String() string    { return fmt.Sprintf("%gm", m) }
func (f Feet) String() string     { return fmt.Sprintf("%gft", f) }
func (k Kilogram) String() string { return fmt.Sprintf("%gkg", k) }
func (p Pound) String() string    { return fmt.Sprintf("%glb", p) }

func MToF(m Meter) Feet     { return Feet(m * 1200 / 3937) }
func FToM(f Feet) Meter     { return Meter(f * 3937 / 1200) }
func KToP(k Kilogram) Pound { return Pound(k / 0.45359237) }
func PToK(p Pound) Kilogram { return Kilogram(p * 0.45359237) }

func main() {
	//从命令行读取输入
	//命令行无输入,从标准输入读取
	var args []string
	if len(os.Args) > 1 {
		args = os.Args[1:]
	} else {
		r := bufio.NewReader(os.Stdin)
		s, err := r.ReadString('\n')
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error: %v\n", err)
			os.Exit(1)
		}
		args = strings.Fields(s)
	}
	//读取完输入,进行转换
	for _, v := range args {

		i, err := strconv.ParseFloat(v, 64)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error: %v\n", err)
			os.Exit(1)
		}
		fmt.Printf("%v = %v, %v = %v\n%v = %v, %v = %v\n\n", Meter(i), MToF(Meter(i)), Feet(i), FToM(Feet(i)), Kilogram(i), KToP(Kilogram(i)), Pound(i), PToK(Pound(i)))
	}
}

执行结果如下,1,2,3为输入的值。

1 2 3
1m = 0.3048006096012192ft, 1ft = 3.2808333333333333m 
1kg = 2.2046226218487757lb, 1lb = 0.45359237kg       

2m = 0.6096012192024384ft, 2ft = 6.5616666666666665m 
2kg = 4.409245243697551lb, 2lb = 0.90718474kg        

3m = 0.9144018288036576ft, 3ft = 9.8425m
3kg = 6.613867865546327lb, 3lb = 1.3607771100000001kg

练习 2.3: 重写PopCount函数,用一个循环代替单一的表达式。比较两个版本的性能。

test.go

//package popcount
package main

// pc[i] is the population count of i.
var pc [256]byte

func init() {
	for i := range pc {
		pc[i] = pc[i/2] + byte(i&1)
	}
}

// PopCount returns the population count (number of set bits) of x.
func PopCount(x uint64) int {
	return int(pc[byte(x>>(0*8))] +
		pc[byte(x>>(1*8))] +
		pc[byte(x>>(2*8))] +
		pc[byte(x>>(3*8))] +
		pc[byte(x>>(4*8))] +
		pc[byte(x>>(5*8))] +
		pc[byte(x>>(6*8))] +
		pc[byte(x>>(7*8))])
}

func PopCountLoop(x uint64) int {
	n := 0
	for i := 0; i < 8; i++ {
		n += int(pc[byte(x>>(i*8))])
	}
	return n
}

t_test.go

package main

import (
	"testing"
)

func BenchmarkPopCount(b *testing.B) {
	for i := 0; i < b.N; i++ {
		PopCount(0x1234567890ABCDEF)
	}
}

func BenchmarkPopCountLoop(b *testing.B) {
	for i := 0; i < b.N; i++ {
		PopCountLoop(0x1234567890ABCDEF)
	}
}

测试结果:

goos: windows
goarch: amd64
pkg: hello
cpu: 11th Gen Intel(R) Core(TM) i7-11800H @ 2.30GHz
BenchmarkPopCount
BenchmarkPopCount-16            1000000000               0.2256 ns/op
BenchmarkPopCountLoop
BenchmarkPopCountLoop-16        402732540                2.889 ns/op
PASS

练习 2.4: 用移位算法重写PopCount函数,每次测试最右边的1bit,然后统计总数。比较和查表算法的性能差异。

test.go

//package popcount
package main

// pc[i] is the population count of i.
var pc [256]byte

func init() {
	for i := range pc {
		pc[i] = pc[i/2] + byte(i&1)
	}
}

// PopCount returns the population count (number of set bits) of x.
func PopCount(x uint64) int {
	return int(pc[byte(x>>(0*8))] +
		pc[byte(x>>(1*8))] +
		pc[byte(x>>(2*8))] +
		pc[byte(x>>(3*8))] +
		pc[byte(x>>(4*8))] +
		pc[byte(x>>(5*8))] +
		pc[byte(x>>(6*8))] +
		pc[byte(x>>(7*8))])
}

func PopCountLoop(x uint64) int {
	n := 0
	for i := 0; i < 8; i++ {
		n += int(pc[byte(x>>(i*8))])
	}
	return n
}

func PopCountBitShift(x uint64) int {
	n := 0
	for i := 0; i < 64; i++ {
		if (x>>i)&1 == 1 {
			n += 1
		}
	}
	return n
}

t_test.go

package main

import (
	"testing"
)

func BenchmarkPopCount(b *testing.B) {
	for i := 0; i < b.N; i++ {
		PopCount(0x1234567890ABCDEF)
	}
}

func BenchmarkPopCountLoop(b *testing.B) {
	for i := 0; i < b.N; i++ {
		PopCountLoop(0x1234567890ABCDEF)
	}
}
func BenchmarkPopCountBitShift(b *testing.B) {
	for i := 0; i < b.N; i++ {
		PopCountBitShift(0x1234567890ABCDEF)
	}
}

测试结果

goos: windows
goarch: amd64
pkg: hello
cpu: 11th Gen Intel(R) Core(TM) i7-11800H @ 2.30GHz
BenchmarkPopCount
BenchmarkPopCount-16                    1000000000               0.2262 ns/op
BenchmarkPopCountLoop
BenchmarkPopCountLoop-16                406502136                2.978 ns/op
BenchmarkPopCountBitShift
BenchmarkPopCountBitShift-16            59245800                20.19 ns/op
PASS

练习 2.5: 表达式x&(x-1)用于将x的最低的一个非零的bit位清零。使用这个算法重写PopCount函数,然后比较性能。

test.go

func PopCountBitClear(x uint64) int {
	n := 0
	for x != 0 {
		x = x & (x - 1)
		n++
	}
	return n
}

 t_test.go

func BenchmarkPopCountBitClear(b *testing.B) {
	for i := 0; i < b.N; i++ {
		PopCountBitClear(0x1234567890ABCDEF)
	}
}

测试结果-单独测试

goos: windows
goarch: amd64
pkg: hello
cpu: 11th Gen Intel(R) Core(TM) i7-11800H @ 2.30GHz
BenchmarkPopCountBitClear
BenchmarkPopCountBitClear-16            100846917               15.84 ns/op
PASS

 总体测试

goos: windows
goarch: amd64
pkg: hello
cpu: 11th Gen Intel(R) Core(TM) i7-11800H @ 2.30GHz
BenchmarkPopCount
BenchmarkPopCount-16                    1000000000               0.2164 ns/op
BenchmarkPopCountLoop
BenchmarkPopCountLoop-16                416805601                2.928 ns/op
BenchmarkPopCountBitShift
BenchmarkPopCountBitShift-16            66856837                20.35 ns/op
BenchmarkPopCountBitClear
BenchmarkPopCountBitClear-16            100000000               17.29 ns/op
PASS

 

posted @ 2022-03-11 16:59  随风而逝的白色相簿  阅读(184)  评论(0编辑  收藏  举报