本文整理汇总了Golang中math/rand.Int63函数的典型用法代码示例。如果您正苦于以下问题:Golang Int63函数的具体用法?Golang Int63怎么用?Golang Int63使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Int63函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestARC_RandomOps
func TestARC_RandomOps(t *testing.T) {
size := 128
l, err := NewARC(128)
if err != nil {
t.Fatalf("err: %v", err)
}
n := 200000
for i := 0; i < n; i++ {
key := rand.Int63() % 512
r := rand.Int63()
switch r % 3 {
case 0:
l.Add(key, key)
case 1:
l.Get(key)
case 2:
l.Remove(key)
}
if l.t1.Len()+l.t2.Len() > size {
t.Fatalf("bad: t1: %d t2: %d b1: %d b2: %d p: %d",
l.t1.Len(), l.t2.Len(), l.b1.Len(), l.b2.Len(), l.p)
}
if l.b1.Len()+l.b2.Len() > size {
t.Fatalf("bad: t1: %d t2: %d b1: %d b2: %d p: %d",
l.t1.Len(), l.t2.Len(), l.b1.Len(), l.b2.Len(), l.p)
}
}
}
示例2: TestGenCtxKey
func TestGenCtxKey(t *testing.T) {
t.Log("test gen ctx key map")
ctxKeyMap := make(map[string]int64, 10)
rand.Seed(100)
ctx := rand.Int63() //int64(1000)
key := fmt.Sprintf("%x", ctx)
t.Logf("key value %s", key)
ctxKeyMap[key] = ctx
ctx1 := rand.Int63()
key1 := fmt.Sprintf("%x", ctx1)
t.Logf("key1 value %s", key1)
ctxKeyMap[key1] = ctx1
if ctxKeyMap["a"] != 0 {
t.Error("notfound map value is not 0")
} else {
t.Log("notfound map value is 0")
}
if ctxKeyMap[key] != ctx {
t.Errorf("key is not in map, get ctx value=%d", ctxKeyMap[key])
} else {
t.Log("test ok...")
}
}
示例3: createNoise
func createNoise(win ui.Window, screen draw.Image) {
var rnd, rnd2 uint64
var rnd16a, rnd16b, rnd16c, rnd16d uint16
var img [240 * 320 * 4]byte
// Populate the image with pixel data
for {
for i := 0; i < len(img); i += 256 {
rnd = uint64(rand.Int63())
if (i % 63) == 0 {
rnd2 = uint64(rand.Int63())
}
rnd |= rnd2 & 1 << 63 // we have to set the 64'th bit from the rand.Int63() manualy
rnd16a = uint16(rnd & 0x000000000000FFFF)
rnd16b = uint16((rnd >> 16) & 0x000000000000FFFF)
rnd16c = uint16((rnd >> 32) & 0x000000000000FFFF)
rnd16d = uint16((rnd >> 48) & 0x000000000000FFFF)
copy(img[i:i+64], bw[rnd16a][:])
copy(img[i+64:i+128], bw[rnd16b][:])
copy(img[i+128:i+192], bw[rnd16c][:])
copy(img[i+192:i+256], bw[rnd16d][:])
rnd2 = rnd2 >> 1 // rotate to next random bit
}
// Copy pixel data to the screen
copy(screen.(*image.RGBA).Pix, img[:])
frameCount <- 1
win.FlushImage()
}
}
示例4: StartServer
//
// servers[] contains the ports of the set of
// servers that will cooperate via Paxos to
// form the fault-tolerant key/value service.
// me is the index of the current server in servers[].
//
func StartServer(servers []string, me int) *KVPaxos {
// this call is all that's needed to persuade
// Go's RPC library to marshall/unmarshall
// struct Op.
gob.Register(Op{})
kv := new(KVPaxos)
kv.me = me
// Your initialization code here.
kv.mydb = map[string]string{}
kv.history = map[int64]string{}
kv.DoneInst = 0
rpcs := rpc.NewServer()
rpcs.Register(kv)
kv.px = paxos.Make(servers, me, rpcs)
os.Remove(servers[me])
l, e := net.Listen("unix", servers[me])
if e != nil {
log.Fatal("listen error: ", e)
}
kv.l = l
// please do not change any of the following code,
// or do anything to subvert it.
go func() {
for kv.dead == false {
conn, err := kv.l.Accept()
if err == nil && kv.dead == false {
if kv.unreliable && (rand.Int63()%1000) < 100 {
// discard the request.
conn.Close()
} else if kv.unreliable && (rand.Int63()%1000) < 200 {
// process the request but force discard of reply.
c1 := conn.(*net.UnixConn)
f, _ := c1.File()
err := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)
if err != nil {
fmt.Printf("shutdown: %v\n", err)
}
go rpcs.ServeConn(conn)
} else {
go rpcs.ServeConn(conn)
}
} else if err == nil {
conn.Close()
}
if err != nil && kv.dead == false {
fmt.Printf("KVPaxos(%v) accept: %v\n", me, err.Error())
kv.kill()
}
}
}()
return kv
}
示例5: Test_Replay
func Test_Replay(test *testing.T) {
type mh struct {
hash []byte
time int64
}
var h [5000]*mh
for i := 0; i < 5000; i++ {
h[i] = new(mh)
h[i].hash = fct.Sha([]byte(fmt.Sprintf("h%d", i))).Bytes()
h[i].time = now + (rand.Int63() % 24 * hour) - 12*hour
if !IsTSValid_(h[i].hash, h[i].time, now) {
fmt.Println("Failed Test ", i, "first")
test.Fail()
return
}
if IsTSValid_(h[i].hash, h[i].time, now) {
fmt.Println("Failed Test ", i, "second")
test.Fail()
return
}
now += rand.Int63() % hour
for j := 0; j < i; j++ {
if IsTSValid_(h[i].hash, h[i].time, hour) {
fmt.Println("Failed Test ", i, j, "repeat")
test.Fail()
return
}
}
}
}
示例6: benchTree
func benchTree(b *testing.B, n int, put, get bool) {
fillBenchTree(b, n)
b.StopTimer()
oldprocs := runtime.GOMAXPROCS(runtime.NumCPU())
defer runtime.GOMAXPROCS(oldprocs)
var keys [][]byte
var vals [][]byte
for i := 0; i < b.N; i++ {
keys = append(keys, murmur.HashString(fmt.Sprint(rand.Int63())))
vals = append(vals, []byte(fmt.Sprint(rand.Int63())))
}
var k []byte
var v []byte
b.StartTimer()
for i := 0; i < b.N; i++ {
k = benchmarkTestKeys[i%len(benchmarkTestKeys)]
v = benchmarkTestValues[i%len(benchmarkTestValues)]
if put {
benchmarkTestTree.Put(k, v, 1)
}
if get {
j, _, existed := benchmarkTestTree.Get(k)
if bytes.Compare(j, v) != 0 {
b.Fatalf("%v should contain %v, but got %v, %v", benchmarkTestTree.Describe(), v, j, existed)
}
}
}
}
示例7: CreatePath
func (p *FileResource) CreatePath(req Request, cxt Context) (string, Request, Context, int, error) {
frc := cxt.(FileResourceContext)
if frc.IsDir() {
newPath := filepath.Join(frc.FullPath(), string(rand.Int63()))
frc2 := NewFileResourceContextWithPath(newPath)
for frc2.Exists() {
newPath = filepath.Join(frc.FullPath(), string(rand.Int63()))
frc2 = NewFileResourceContextWithPath(newPath)
}
frc = frc2
} else if frc.Exists() {
p := frc.FullPath()
dir, tail := path.Split(p)
ext := path.Ext(tail)
basename := tail
uniquify := time.Now().UTC().Format(".20060102.150405")
if len(ext) > 0 {
basename = tail[:len(tail)-len(ext)] + uniquify
frc.SetFullPath(path.Join(dir, basename+ext))
for counter := 1; frc.Exists(); counter++ {
frc.SetFullPath(path.Join(dir, basename+"."+strconv.Itoa(counter)+ext))
}
} else {
basename = basename + uniquify
frc.SetFullPath(path.Join(dir, basename))
for counter := 1; frc.Exists(); counter++ {
frc.SetFullPath(path.Join(dir, basename+"."+strconv.Itoa(counter)))
}
}
}
log.Print("[FileResource]: Will use path ", frc.FullPath())
return frc.FullPath(), req, frc, 0, nil
}
示例8: Test2Q_RandomOps
func Test2Q_RandomOps(t *testing.T) {
size := 128
l, err := New2Q(128)
if err != nil {
t.Fatalf("err: %v", err)
}
n := 200000
for i := 0; i < n; i++ {
key := rand.Int63() % 512
r := rand.Int63()
switch r % 3 {
case 0:
l.Add(key, key)
case 1:
l.Get(key)
case 2:
l.Remove(key)
}
if l.recent.Len()+l.frequent.Len() > size {
t.Fatalf("bad: recent: %d freq: %d",
l.recent.Len(), l.frequent.Len())
}
}
}
示例9: KeyGen
// AES-256 Friendly, Great for Session ID's
func KeyGen() string {
const keyLen = 32
curtime := time.Now()
second := uint64ToByte(uint64(curtime.Unix()))
nano := uint64ToByte(uint64(curtime.UnixNano()))
rand1 := uint64ToByte(uint64(rand.Int63()))
rand2 := uint64ToByte(uint64(rand.Int63()))
b := []byte{}
for key, value := range second {
b = append(b, value, rand1[key])
}
for key, value := range nano {
b = append(b, value, rand2[key])
}
hash := sha256.New()
defer hash.Reset()
hash.Write(b)
b = hash.Sum(nil)
str := base64.URLEncoding.EncodeToString(b)
return str[:keyLen]
}
示例10: Make
//
// the application wants to create a paxos peer.
// the ports of all the paxos peers (including this one)
// are in peers[]. this servers port is peers[me].
//
func Make(peers []string, me int, rpcs *rpc.Server) *Paxos {
px := &Paxos{}
px.peers = peers
px.me = me
// Your initialization code here.
if rpcs != nil {
// caller will create socket &c
rpcs.Register(px)
} else {
rpcs = rpc.NewServer()
rpcs.Register(px)
// prepare to receive connections from clients.
// change "unix" to "tcp" to use over a network.
os.Remove(peers[me]) // only needed for "unix"
l, e := net.Listen("unix", peers[me])
if e != nil {
log.Fatal("listen error: ", e)
}
px.l = l
// please do not change any of the following code,
// or do anything to subvert it.
// create a thread to accept RPC connections
go func() {
for px.dead == false {
conn, err := px.l.Accept()
if err == nil && px.dead == false {
if px.unreliable && (rand.Int63()%1000) < 100 {
// discard the request.
conn.Close()
} else if px.unreliable && (rand.Int63()%1000) < 200 {
// process the request but force discard of reply.
c1 := conn.(*net.UnixConn)
f, _ := c1.File()
err := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)
if err != nil {
fmt.Printf("shutdown: %v\n", err)
}
px.rpcCount++
go rpcs.ServeConn(conn)
} else {
px.rpcCount++
go rpcs.ServeConn(conn)
}
} else if err == nil {
conn.Close()
}
if err != nil && px.dead == false {
fmt.Printf("Paxos(%v) accept: %v\n", me, err.Error())
}
}
}()
}
return px
}
示例11: MakeTestTasksN
func MakeTestTasksN(height, width, connectivity int) graph.Tasks {
t := make(graph.Tasks)
levels := make([][]*graph.Task, height)
for i := range levels {
levels[i] = make([]*graph.Task, width)
for j := range levels[i] {
task := &graph.Task{
Id: graph.TaskID(strconv.FormatInt(rand.Int63(), 10)),
Start: rand.Int63(),
End: rand.Int63(),
Completed: rand.Int()%2 == 0,
Dependencies: graph.MakeTaskIDSet(),
}
t[task.Id] = task
levels[i][j] = task
}
}
for depth, level := range levels[:height-1] {
for _, task := range level {
connections := rand.Int31n(int32(connectivity))
for i := 0; i < int(connections); i++ {
row, col := rand.Int31n(int32(height-depth-1)), rand.Int31n(int32(width))
task.Dependencies.Add(levels[depth+int(row)+1][col].Id)
}
}
}
return t
}
示例12: StartServer
//
// servers[] contains the ports of the set of
// servers that will cooperate via Paxos to
// form the fault-tolerant key/value service.
// me is the index of the current server in servers[].
//
func StartServer(servers []string, me int) *KVPaxos {
// call gob.Register on structures you want
// Go's RPC library to marshall/unmarshall.
gob.Register(Op{})
kv := new(KVPaxos)
kv.me = me
// initialization
kv.kvData = make(map[string]string)
kv.preReply = make(map[string]*Op)
kv.seqChan = make(map[int]chan *Op)
kv.maxInstanceID = -1
rpcs := rpc.NewServer()
rpcs.Register(kv)
kv.px = paxos.Make(servers, me, rpcs)
os.Remove(servers[me])
l, e := net.Listen("unix", servers[me])
if e != nil {
log.Fatal("listen error: ", e)
}
kv.l = l
// please do not change any of the following code,
// or do anything to subvert it.
go func() {
for kv.dead == false {
conn, err := kv.l.Accept()
if err == nil && kv.dead == false {
if kv.unreliable && (rand.Int63()%1000) < 100 {
// discard the request.
conn.Close()
} else if kv.unreliable && (rand.Int63()%1000) < 200 {
// process the request but force discard of reply.
c1 := conn.(*net.UnixConn)
f, _ := c1.File()
err := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)
if err != nil {
fmt.Printf("shutdown: %v\n", err)
}
go rpcs.ServeConn(conn)
} else {
go rpcs.ServeConn(conn)
}
} else if err == nil {
conn.Close()
}
if err != nil && kv.dead == false {
fmt.Printf("KVPaxos(%v) accept: %v\n", me, err.Error())
kv.kill()
}
}
}()
go kv.updateStatus()
return kv
}
示例13: BenchmarkARC_Freq
func BenchmarkARC_Freq(b *testing.B) {
l, err := NewARC(8192)
if err != nil {
b.Fatalf("err: %v", err)
}
trace := make([]int64, b.N*2)
for i := 0; i < b.N*2; i++ {
if i%2 == 0 {
trace[i] = rand.Int63() % 16384
} else {
trace[i] = rand.Int63() % 32768
}
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
l.Add(trace[i], trace[i])
}
var hit, miss int
for i := 0; i < b.N; i++ {
_, ok := l.Get(trace[i])
if ok {
hit++
} else {
miss++
}
}
b.Logf("hit: %d miss: %d ratio: %f", hit, miss, float64(hit)/float64(miss))
}
示例14: StartServer
func StartServer(vshost string, me string) *PBServer {
pb := new(PBServer)
pb.me = me
pb.vs = viewservice.MakeClerk(me, vshost)
// Your pb.* initializations here.
pb.view = viewservice.View{}
pb.content = make(map[string]string)
pb.client = make(map[string]string)
rpcs := rpc.NewServer()
rpcs.Register(pb)
os.Remove(pb.me)
l, e := net.Listen("unix", pb.me)
if e != nil {
log.Fatal("listen error: ", e)
}
pb.l = l
// please do not change any of the following code,
// or do anything to subvert it.
go func() {
for pb.isdead() == false {
conn, err := pb.l.Accept()
if err == nil && pb.isdead() == false {
if pb.isunreliable() && (rand.Int63()%1000) < 100 {
// discard the request.
conn.Close()
} else if pb.isunreliable() && (rand.Int63()%1000) < 200 {
// process the request but force discard of reply.
c1 := conn.(*net.UnixConn)
f, _ := c1.File()
err := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)
if err != nil {
fmt.Printf("shutdown: %v\n", err)
}
go rpcs.ServeConn(conn)
} else {
go rpcs.ServeConn(conn)
}
} else if err == nil {
conn.Close()
}
if err != nil && pb.isdead() == false {
fmt.Printf("PBServer(%v) accept: %v\n", me, err.Error())
pb.kill()
}
}
}()
go func() {
for pb.isdead() == false {
pb.tick()
time.Sleep(viewservice.PingInterval)
}
}()
return pb
}
示例15: TestPostSpans
func TestPostSpans(t *testing.T) {
rand.Seed(time.Now().UnixNano())
traceID := fmt.Sprintf("%016x", rand.Int63())
id, name, duration := fmt.Sprintf("%016x", rand.Int63()), "test_post_spans", int64(time.Microsecond*1000)
id2, name2, duration2 := fmt.Sprintf("%016x", rand.Int63()), "test_post_spans2", int64(time.Microsecond*1000)
debug := true
ipv4, port, serviceName1, serviceName2 := "127.0.0.1", int64(80), "store_test", "store_test2"
ep1 := &models.Endpoint{IPV4: &ipv4, Port: &port, ServiceName: &serviceName1}
ep2 := &models.Endpoint{IPV4: &ipv4, Port: &port, ServiceName: &serviceName2}
ts := time.Now().UnixNano() / 1000
annKey1, annValue1 := "key1", base64.StdEncoding.EncodeToString([]byte("value1"))
req := []*models.Span{
{
TraceID: &traceID,
ID: &id,
Name: &name,
ParentID: nil,
Timestamp: ts,
Duration: &duration,
Debug: &debug,
Annotations: []*models.Annotation{
{ep1, Int64(ts + 100), models.AnnotationValue_SERVER_RECV.Addr()},
{ep1, Int64(ts + 200), models.AnnotationValue_CLIENT_SEND.Addr()},
{ep1, Int64(ts + 300), models.AnnotationValue_CLIENT_RECV.Addr()},
{ep1, Int64(ts + 400), models.AnnotationValue_SERVER_SEND.Addr()},
},
},
{
TraceID: &traceID,
ID: &id2,
Name: &name2,
ParentID: &id,
Timestamp: ts + 200,
Duration: &duration2,
Debug: &debug,
Annotations: []*models.Annotation{
{ep2, Int64(ts + 210), models.AnnotationValue_SERVER_RECV.Addr()},
{ep2, Int64(ts + 220), models.AnnotationValue_CLIENT_SEND.Addr()},
{ep2, Int64(ts + 230), models.AnnotationValue_CLIENT_RECV.Addr()},
{ep2, Int64(ts + 240), models.AnnotationValue_SERVER_SEND.Addr()},
},
BinaryAnnotations: []*models.BinaryAnnotation{
{models.AnnotationType_STRING.Addr(), ep2, &annKey1, &annValue1},
},
}}
reqData, _ := json.Marshal(req)
resp, err := http.Post("http://localhost:8081/api/v1/spans", "application/json", bytes.NewReader(reqData))
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusAccepted {
msg, _ := ioutil.ReadAll(resp.Body)
t.Logf("%s", msg)
t.Fatal(resp.StatusCode)
}
}