go语言实现func bc Blockchain PrintBlockTimestamp答应每个区块的耗时和二、生成100个区块平均时间在6-10秒的范围
- 实现PrintBlockTimestamp函数
func (bc *Blockchain) PrintBlockTimestamp() {
for _, block := range bc.blocks {
fmt.Printf("Block %s took %d seconds\n", block.Hash, block.Timestamp.Sub(block.PrevBlockTimestamp).Seconds())
}
}
- 生成100个区块,并统计平均时间
func main() {
bc := NewBlockchain()
start := time.Now()
for i := 0; i < 100; i++ {
bc.AddBlock(fmt.Sprintf("Block %d", i))
time.Sleep(time.Duration(rand.Intn(5)+6) * time.Second)
}
end := time.Now()
bc.PrintBlockTimestamp()
fmt.Printf("Average block time: %.2f seconds\n", end.Sub(start).Seconds()/float64(len(bc.blocks)))
}
在每个区块生成时,程序会随机等待6-10秒,然后计算每个区块的耗时并输出。最后统计所有区块的生成时间并计算平均值输出。
原文地址: https://www.cveoy.top/t/topic/4r2 著作权归作者所有。请勿转载和采集!