Skip to content

Commit bbd53a6

Browse files
authored
chore: use time.Since instead of time.Now().Sub (#12801)
1 parent ac85fd8 commit bbd53a6

File tree

13 files changed

+38
-42
lines changed

13 files changed

+38
-42
lines changed

chain/sub/incoming.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,10 @@ import (
3030
"github.com/filecoin-project/lotus/metrics"
3131
)
3232

33-
var log = logging.Logger("sub")
34-
var DefaultHashFunction = uint64(mh.BLAKE2B_MIN + 31)
33+
var (
34+
log = logging.Logger("sub")
35+
DefaultHashFunction = uint64(mh.BLAKE2B_MIN + 31)
36+
)
3537

3638
var msgCidPrefix = cid.Prefix{
3739
Version: 1,
@@ -169,7 +171,6 @@ func fetchCids(
169171
cids []cid.Cid,
170172
cb func(int, blocks.Block) error,
171173
) error {
172-
173174
ctx, cancel := context.WithCancel(ctx)
174175
defer cancel()
175176

@@ -327,7 +328,7 @@ func (mv *MessageValidator) Validate(ctx context.Context, pid peer.ID, msg *pubs
327328

328329
start := time.Now()
329330
defer func() {
330-
ms := time.Now().Sub(start).Microseconds()
331+
ms := time.Since(start).Microseconds()
331332
stats.Record(ctx, metrics.MessageValidationDuration.M(float64(ms)/1000))
332333
}()
333334

@@ -394,7 +395,7 @@ func (mv *MessageValidator) validateLocalMessage(ctx context.Context, msg *pubsu
394395

395396
start := time.Now()
396397
defer func() {
397-
ms := time.Now().Sub(start).Microseconds()
398+
ms := time.Since(start).Microseconds()
398399
stats.Record(ctx, metrics.MessageValidationDuration.M(float64(ms)/1000))
399400
}()
400401

cli/info.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ func infoCmdAct(cctx *cli.Context) error {
4545
}
4646

4747
fmt.Printf("Network: %s\n", network.NetworkName)
48-
fmt.Printf("StartTime: %s (started at %s)\n", time.Now().Sub(start).Truncate(time.Second), start.Truncate(time.Second))
48+
fmt.Printf("StartTime: %s (started at %s)\n", time.Since(start).Truncate(time.Second), start.Truncate(time.Second))
4949
fmt.Print("Chain: ")
5050
err = SyncBasefeeCheck(ctx, fullapi)
5151
if err != nil {
@@ -75,7 +75,7 @@ func infoCmdAct(cctx *cli.Context) error {
7575
fmt.Printf("%s (check %s)\n", color.RedString("⚠ %d Active alerts", len(activeAlerts)), color.YellowString("lotus log alerts"))
7676
}
7777

78-
//Chain health calculated as percentage: amount of blocks in last finality / very healthy amount of blocks in a finality (900 epochs * 5 blocks per tipset)
78+
// Chain health calculated as percentage: amount of blocks in last finality / very healthy amount of blocks in a finality (900 epochs * 5 blocks per tipset)
7979
health := (100 * (900 * status.ChainStatus.BlocksPerTipsetLastFinality) / (900 * 5))
8080
switch {
8181
case health > 85:
@@ -173,7 +173,6 @@ func infoCmdAct(cctx *cli.Context) error {
173173
return err
174174
}
175175
return tw.Flush()
176-
177176
}
178177

179178
func SyncBasefeeCheck(ctx context.Context, fullapi v1api.FullNode) error {
@@ -186,9 +185,9 @@ func SyncBasefeeCheck(ctx context.Context, fullapi v1api.FullNode) error {
186185
case time.Now().Unix()-int64(head.MinTimestamp()) < int64(buildconstants.BlockDelaySecs*3/2): // within 1.5 epochs
187186
fmt.Printf("[%s]", color.GreenString("sync ok"))
188187
case time.Now().Unix()-int64(head.MinTimestamp()) < int64(buildconstants.BlockDelaySecs*5): // within 5 epochs
189-
fmt.Printf("[%s]", color.YellowString("sync slow (%s behind)", time.Now().Sub(time.Unix(int64(head.MinTimestamp()), 0)).Truncate(time.Second)))
188+
fmt.Printf("[%s]", color.YellowString("sync slow (%s behind)", time.Since(time.Unix(int64(head.MinTimestamp()), 0)).Truncate(time.Second)))
190189
default:
191-
fmt.Printf("[%s]", color.RedString("sync behind! (%s behind)", time.Now().Sub(time.Unix(int64(head.MinTimestamp()), 0)).Truncate(time.Second)))
190+
fmt.Printf("[%s]", color.RedString("sync behind! (%s behind)", time.Since(time.Unix(int64(head.MinTimestamp()), 0)).Truncate(time.Second)))
192191
}
193192
basefee := head.MinTicketBlock().ParentBaseFee
194193
gasCol := []color.Attribute{color.FgBlue}

cmd/lotus-miner/info.go

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ func infoCmdAct(cctx *cli.Context) error {
8181
if err != nil {
8282
return err
8383
}
84-
fmt.Printf("StartTime: %s (started at %s)\n", time.Now().Sub(start).Truncate(time.Second), start.Truncate(time.Second))
84+
fmt.Printf("StartTime: %s (started at %s)\n", time.Since(start).Truncate(time.Second), start.Truncate(time.Second))
8585

8686
fmt.Print("Chain: ")
8787

@@ -135,7 +135,6 @@ func handleMiningInfo(ctx context.Context, cctx *cli.Context, fullapi v1api.Full
135135

136136
// Sector size
137137
mi, err := fullapi.StateMinerInfo(ctx, maddr, types.EmptyTSK)
138-
139138
if err != nil {
140139
return err
141140
}
@@ -166,7 +165,6 @@ func handleMiningInfo(ctx context.Context, cctx *cli.Context, fullapi v1api.Full
166165
),
167166
)
168167
secCounts, err := fullapi.StateMinerSectorCount(ctx, maddr, types.EmptyTSK)
169-
170168
if err != nil {
171169
return err
172170
}
@@ -267,7 +265,6 @@ func handleMiningInfo(ctx context.Context, cctx *cli.Context, fullapi v1api.Full
267265
colorTokenAmount(" Available: %s\n", availBalance)
268266

269267
mb, err := fullapi.StateMarketBalance(ctx, maddr, types.EmptyTSK)
270-
271268
if err != nil {
272269
return xerrors.Errorf("getting market balance: %w", err)
273270
}
@@ -278,7 +275,6 @@ func handleMiningInfo(ctx context.Context, cctx *cli.Context, fullapi v1api.Full
278275
colorTokenAmount(" Available: %s\n", big.Sub(mb.Escrow, mb.Locked))
279276

280277
wb, err := fullapi.WalletBalance(ctx, mi.Worker)
281-
282278
if err != nil {
283279
return xerrors.Errorf("getting worker balance: %w", err)
284280
}

cmd/lotus-miner/proving.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,12 +239,12 @@ It will not send any messages to the chain.`,
239239

240240
start := time.Now()
241241
res, err := minerApi.ComputeWindowPoSt(ctx, dlIdx, types.EmptyTSK)
242-
fmt.Printf("Took %s\n", time.Now().Sub(start))
242+
fmt.Printf("Took %s\n", time.Since(start))
243243
if err != nil {
244244
return err
245245
}
246246

247-
//convert sector information into easily readable information
247+
// convert sector information into easily readable information
248248
type PoStPartition struct {
249249
Index uint64
250250
Skipped []uint64

cmd/lotus-miner/sealing.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -286,7 +286,7 @@ var sealingJobsCmd = &cli.Command{
286286
}
287287
dur := "n/a"
288288
if !l.Start.IsZero() {
289-
dur = time.Now().Sub(l.Start).Truncate(time.Millisecond * 100).String()
289+
dur = time.Since(l.Start).Truncate(time.Millisecond * 100).String()
290290
}
291291

292292
hostname, ok := workerHostnames[l.wid]

cmd/lotus-miner/storage.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,7 @@ var storageListCmd = &cli.Command{
351351
fmt.Printf("\t%s: %s:\n", color.RedString("Error"), err)
352352
continue
353353
}
354-
ping := time.Now().Sub(pingStart)
354+
ping := time.Since(pingStart)
355355

356356
safeRepeat := func(s string, count int) string {
357357
if count < 0 {
@@ -360,7 +360,7 @@ var storageListCmd = &cli.Command{
360360
return strings.Repeat(s, count)
361361
}
362362

363-
var barCols = int64(50)
363+
barCols := int64(50)
364364

365365
// filesystem use bar
366366
{
@@ -738,7 +738,6 @@ var storageListSectorsCmd = &cli.Command{
738738
}
739739

740740
for _, info := range si {
741-
742741
list = append(list, entry{
743742
id: sector,
744743
storage: info.ID,

miner/warmup.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ out:
8484
return xerrors.Errorf("failed to compute proof: %w", err)
8585
}
8686

87-
log.Infow("winning PoSt warmup successful", "took", time.Now().Sub(start))
87+
log.Infow("winning PoSt warmup successful", "took", time.Since(start))
8888
return nil
8989
}
9090

storage/paths/fetch.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ func fetch(ctx context.Context, url, outname string, header http.Header) (rerr e
3737
start := time.Now()
3838
var bytes int64
3939
defer func() {
40-
took := time.Now().Sub(start)
40+
took := time.Since(start)
4141
mibps := float64(bytes) / 1024 / 1024 * float64(time.Second) / float64(took)
4242
log.Infow("Fetch done", "url", url, "out", outname, "took", took.Round(time.Millisecond), "bytes", bytes, "MiB/s", mibps, "err", rerr)
4343
}()

storage/paths/local.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ func (p *path) stat(ls LocalStorage, newReserve ...statExistingSectorForReservat
144144
}
145145

146146
if stat.Reserved < 0 {
147-
//log.Warnf("negative reserved storage: p.reserved=%d, reserved: %d", p.reserved, stat.Reserved)
147+
// log.Warnf("negative reserved storage: p.reserved=%d, reserved: %d", p.reserved, stat.Reserved)
148148
var jsonReservations []map[string]interface{}
149149
for id, res := range p.reservations {
150150
jsonReservations = append(jsonReservations, map[string]interface{}{
@@ -182,8 +182,8 @@ func (p *path) stat(ls LocalStorage, newReserve ...statExistingSectorForReservat
182182
}
183183
}
184184

185-
if time.Now().Sub(start) > 5*time.Second {
186-
log.Warnw("slow storage stat", "took", time.Now().Sub(start), "reservations", len(p.reservations))
185+
if took := time.Since(start); took > 5*time.Second {
186+
log.Warnw("slow storage stat", "took", took, "reservations", len(p.reservations))
187187
}
188188

189189
return stat, newReserveOnDisk, err
@@ -463,7 +463,8 @@ func (st *Local) reportStorage(ctx context.Context) {
463463
}
464464

465465
func (st *Local) Reserve(ctx context.Context, sid storiface.SectorRef, ft storiface.SectorFileType,
466-
storageIDs storiface.SectorPaths, overheadTab map[storiface.SectorFileType]int, minFreePercentage float64) (func(), error) {
466+
storageIDs storiface.SectorPaths, overheadTab map[storiface.SectorFileType]int, minFreePercentage float64,
467+
) (func(), error) {
467468
ssize, err := sid.ProofType.SectorSize()
468469
if err != nil {
469470
return nil, err
@@ -661,7 +662,6 @@ func (st *Local) AcquireSector(ctx context.Context, sid storiface.SectorRef, exi
661662
}
662663

663664
alloc, err := allocPathOk(si.CanSeal, si.CanStore, si.AllowTypes, si.DenyTypes, si.AllowMiners, si.DenyMiners, fileType, sid.ID.Miner)
664-
665665
if err != nil {
666666
log.Debug(err)
667667
continue
@@ -950,7 +950,7 @@ func (st *Local) GenerateSingleVanillaProof(ctx context.Context, minerID abi.Act
950950
case r := <-resCh:
951951
return r.Unwrap()
952952
case <-ctx.Done():
953-
log.Errorw("failed to generate valilla PoSt proof before context cancellation", "err", ctx.Err(), "duration", time.Now().Sub(start), "cache-id", cacheID, "sealed-id", sealedID, "cache", cache, "sealed", sealed)
953+
log.Errorw("failed to generate valilla PoSt proof before context cancellation", "err", ctx.Err(), "duration", time.Since(start), "cache-id", cacheID, "sealed-id", sealedID, "cache", cache, "sealed", sealed)
954954

955955
// this will leave the GenerateSingleVanillaProof goroutine hanging, but that's still less bad than failing PoSt
956956
return nil, xerrors.Errorf("failed to generate vanilla proof before context cancellation: %w", ctx.Err())

storage/paths/localstorage_cached.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,10 @@ import (
1111
"github.com/filecoin-project/lotus/storage/sealer/storiface"
1212
)
1313

14-
var StatTimeout = 5 * time.Second
15-
var MaxDiskUsageDuration = time.Second
14+
var (
15+
StatTimeout = 5 * time.Second
16+
MaxDiskUsageDuration = time.Second
17+
)
1618

1719
type cachedLocalStorage struct {
1820
base LocalStorage
@@ -61,7 +63,7 @@ func (c *cachedLocalStorage) Stat(path string) (fsutil.FsStat, error) {
6163
c.statLk.Lock()
6264
defer c.statLk.Unlock()
6365

64-
if v, ok := c.stats.Get(path); ok && time.Now().Sub(v.time) < StatTimeout {
66+
if v, ok := c.stats.Get(path); ok && time.Since(v.time) < StatTimeout {
6567
return v.stat, nil
6668
}
6769

@@ -87,7 +89,7 @@ func (c *cachedLocalStorage) DiskUsage(path string) (int64, error) {
8789
entry = v
8890

8991
// if we have recent cached entry, use that
90-
if time.Now().Sub(entry.last.time) < StatTimeout {
92+
if time.Since(entry.last.time) < StatTimeout {
9193
return entry.last.usage, nil
9294
}
9395
} else {
@@ -126,7 +128,7 @@ func (c *cachedLocalStorage) DiskUsage(path string) (int64, error) {
126128
log.Warnw("getting usage is slow, falling back to previous usage",
127129
"path", path,
128130
"fallback", entry.last.usage,
129-
"age", time.Now().Sub(entry.last.time))
131+
"age", time.Since(entry.last.time))
130132
}
131133

132134
return entry.last.usage, nil

0 commit comments

Comments
 (0)