How can I improve the style to avoid so many float64()
s?
func IsInTimeRange(tvalue int32,timeout int){
t := time.Now().Unix()
return int(math.Abs(float64(t)-float64(tvalue))) < timeout
}
3 Answers 3
For example,
package main
import (
"fmt"
"time"
)
func IsInTimeRange(tvalue int32, timeout int) bool {
delta := int(time.Now().Unix() - int64(tvalue))
return -timeout < delta && delta < timeout
}
func main() {}
tvalue int32
will overflow in year 2038, change it to tvalue int64
.
package main
import "time"
func IsInTimeRange(tvalue int64, timeout int) bool {
delta := int(time.Now().Unix() - tvalue)
return -timeout < delta && delta < timeout
}
func main() {}
-
\$\begingroup\$ tvalue maybe negative by bad call. What a pity , there are no function overloading in golang \$\endgroup\$wan zong– wan zong2015年11月23日 12:36:55 +00:00Commented Nov 23, 2015 at 12:36
-
\$\begingroup\$ I have no idea that what's
int64
safe in python with Thrift,so I choose int32. \$\endgroup\$wan zong– wan zong2015年11月23日 12:45:46 +00:00Commented Nov 23, 2015 at 12:45
You seem to convert to float64
only to use math.Abs
. This is complete overkill. Abs
for integers is a trivial (if you can neglect overflow as in your example) if
statement.
(Background: math.Abs
exists to handle NaNs and Infs properly.)
This is not a full answer, but might still be of interest.
As already stated; math.Abs
is overkill for integer absolutes. And writing your own Abs
function is trivial.
But if you want one, the fastest way to do it can be found in the png
package:
func Abs(x int) int {
// intSize is either 32 or 64.
const intSize = 32 << (^uint(0) >> 63)
// m := -1 if x < 0. m := 0 otherwise.
m := x >> (intSize - 1)
// In two's complement representation, the negative number
// of any number (except the smallest one) can be computed
// by flipping all the bits and add 1. This is faster than
// code with a branch.
// See Hacker's Delight, section 2-4.
return (x ^ m) - m
}
tvalue
andtimeout
values. Without a common basis intime.Time
, there is no way to compare them relative to a current time. \$\endgroup\$return
in a function with no return type in its signature. Why not get your code to compile before posting it? \$\endgroup\$