从用户的输入中获取UINT8比服用UINT64更有效吗?
以下代码从用户的输入中获取64位未签名的整数:
package main
import (
"fmt"
"bufio"
"os"
"strconv"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Give me a small integer?")
scanner.Scan()
times, _ := strconv.ParseUint(scanner.Text(), 10, 64)
fmt.Printf("%T\n", times) //real 0m1.900s user 0m0.000s sys 0m0.003s
}
以下代码从用户中需要一个8位的无签名整数:
package main
import (
"fmt"
"bufio"
"os"
"strconv"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Give me a small integer?")
scanner.Scan()
times, _ := strconv.ParseUint(scanner.Text(), 10, 8)
times8bit := uint8(times)
fmt.Printf("%T\n", times8bit) //real 0m2.014s user 0m0.003s sys 0m0.000s
}
这两个摘要都花费了我的CPU时间的大约相同数量(如注释中所示的结果如下所示。 时间
)。
第二个摘要使用的内存少于第一个片段吗?我认为创建另一个变量times8bit
使用比第一个片段使用的内存更多的内存在第二个片段中产生。是这样吗?我知道性能的潜在差异是疏忽大意的,但是还有另一种更有效的方法可以从用户输入中获取未签名的8位整数吗?
The following code takes a 64-bit unsigned integer from it's user's input:
package main
import (
"fmt"
"bufio"
"os"
"strconv"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Give me a small integer?")
scanner.Scan()
times, _ := strconv.ParseUint(scanner.Text(), 10, 64)
fmt.Printf("%T\n", times) //real 0m1.900s user 0m0.000s sys 0m0.003s
}
and the following takes an 8-bit unsigned integer from it's user:
package main
import (
"fmt"
"bufio"
"os"
"strconv"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Give me a small integer?")
scanner.Scan()
times, _ := strconv.ParseUint(scanner.Text(), 10, 8)
times8bit := uint8(times)
fmt.Printf("%T\n", times8bit) //real 0m2.014s user 0m0.003s sys 0m0.000s
}
Both snippets take approximately the same amount of my CPU time(as shown in the comments by the result of time
).
Is the second snippet using less memory than the first? I would think that creating another variable times8bit
results in the second snippet using even more memory than that used by the first snippet. Is that the case? I am aware that the potential difference in performance is negligent, but is there another, a more efficient way of taking an unsigned 8-bit integer from user's input?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论