猿问

goroutine 中 time.Now() 的意外行为

作为尝试熟悉 Go 的一种方式,我正在尝试构建一个(完全不可靠的)随机数生成器。这个想法是对某个 url 进行 100 个 GET 请求,对结果做一些事情并产生一个“随机”数字。
我很想知道在工作组中使用 goroutines 执行请求时代码是否会运行得更快。答案似乎是肯定的,但是当打印出各个请求的计时结果时,goroutine 调用的计时显示出一个有趣的结果。
GET 请求的顺序计时(以微秒为单位):
[25007 30502 25594 40417 31505 18502 20503 19034 19473 18001 36507 25004 28005 19004 20502 20503 20503 20504 20002 19003 20511 18494 20003 21004 20003 20502 20504 19002 19004 21506 29501 30005 31005 21504 20054 22452 19503 19503 20003 19503 21004 18501 18003 20003 20003 19003 19503 20003 23504 18003 20003 19503 19502 19003 20003 20003 20040 21010 18959 20503 34251 27260 30504 25004 22004 20502 20003 19503 20502 20504 19503 22003 19003 19003 20003 20002 18003 19503 19003 18503 20504 18552 18953 18002 20003 19004 21002 18503 20503 19503 20504 20003 20003 21003 46050 19504 18503 19503 19503 19002]

GET 请求的 Goroutine 计时(以微秒为单位):Goroutine
[104518 134570 157528 187533 193535 193535 208036 211041 220039 220242 252044 252044 258045 258045 258045 258045 271047 282050 282050 282050 286050 287050 289051 296052 297552 300052 300678 305553 307053 308054 310556 311069 312055 312555 324056 329558 334559 339559 346061 353562 360563 369564 375065 377566 384067 393569 397069 402570 410072 416572 420573 425574 431076 437576 443078 446577 453579 458580 465081 474583 480584 488085 496122 505588 510589 515590 520591 526592 533593 538596 544595 549596 555097 563098 569600 575100 584101 589604 595604 604106 610606 620609 634111 640611 645613 653119 656616 663116 669117 674118 681119 696122 709123 723627 735629 747631 757632 769635 779137 785139]
调用的计时是增量的,而常规的顺序计时是预期的。我怀疑这可能与对所有 gorotines 进行一次评估的 time.now() 有关,但改组调用并没有改变结果。
这是我到目前为止所拥有的,我知道熵不是衡量随机性的好方法,但由于某些原因我还是将它包含在内:)
首先运行 goroutine,然后运行顺序版本。最后,时间和其他一些东西被打印出来。


慕码人8056858
浏览 168回答 1
1回答

慕工程0101907

这种行为的原因在于 Go 的调度程序(这个问题的较短版本在 golang-nuts)。上面的 goroutines 都在同一时间点开始执行(如计时所示,加上检查 startTime 变量的内存位置证明时间对象不是“回收”),但是一旦它们命中 http.Get() 就会取消调度.&nbsp;计时是递增的,因为 http.Get() 造成了瓶颈,不允许并发执行生成的 goroutine 数量。似乎这里使用了某种 FIFO 队列。推荐观看阅读:解释 Golang I/O 多路复用 netpoller 模型队列、公平性和 Go 调度程序研究等待组的大小,我发现一些值显示出更加一致的时间(而不是增量)。所以我想知道等待组大小对总时间和个人时间的影响是什么。我将上面重构为一个程序,该程序在给定范围内对每个 waitgroupsize 进行多次实验,并将每次运行的总计时和单独计时保存到 sqlite 数据库中。生成的数据集可以很容易地用于 Jupyter Notebook 等。不幸的是,在当前设置下,我只能获得大约 40K 的请求,然后才会受到限制。看我的github对于某些数据集,如果您有兴趣但不想等待数据,因为它需要很长时间才能完成。有趣的结果是,对于小型 wg 大小,并发/顺序比率急剧下降,您会在最后看到连接开始受到限制。该运行当时被手动中止。并发运行时间/顺序运行时间与等待组大小:不同等待组大小的个别时间图。package mainimport (&nbsp; &nbsp; "database/sql"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "log"&nbsp; &nbsp; "net/http"&nbsp; &nbsp; "os"&nbsp; &nbsp; "path/filepath"&nbsp; &nbsp; "runtime"&nbsp; &nbsp; "sync"&nbsp; &nbsp; "time"&nbsp; &nbsp; _ "github.com/mattn/go-sqlite3")///// global varsconst REQUESTS int = 100&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Single run size, performed two times (concurrent and sequential)const URL string = "SET_YOUR_OWN" // Some file on a CDN somewhere; used for the GET requestsconst DBNAME string = "netRand.db" // Name of the db file. Saved next to the executableconst WGMIN int = 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Start range for waitgroup size (inclusive)const WGMAX int = 101&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Stop range for waitgroup size (exclusive)const NREPEAT int = 10&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Number of times to repeat a run for a specific waitgroup size//// typestype timingResult struct {&nbsp; &nbsp; // Container for collecting results before persisting to DB&nbsp; &nbsp; WaitgroupSize&nbsp; &nbsp; &nbsp; &nbsp;int&nbsp; &nbsp; ConcurrentTimingsMs [REQUESTS]int64&nbsp; &nbsp; ConcurrentTotalMs&nbsp; &nbsp;int64&nbsp; &nbsp; SequentialTimingsMs [REQUESTS]int64&nbsp; &nbsp; SequentialTotalMs&nbsp; &nbsp;int64}//// mainfunc main() {&nbsp; &nbsp; db := setupDb()&nbsp; &nbsp; defer db.Close()&nbsp; &nbsp; for i := WGMIN; i < WGMAX; i++ {&nbsp; &nbsp; &nbsp; &nbsp; // waitgroup size range&nbsp; &nbsp; &nbsp; &nbsp; for j := 0; j < NREPEAT; j++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // repeat for more data points&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; timings := requestTimes(i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; persistTimings(timings, db)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("\n======== %v of %v ============\n", j+1, NREPEAT)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("current waitgroup size: %v\n", i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("max waitgroup size: %v\n", WGMAX-1)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}func requestTimes(waitgroupSize int) timingResult {&nbsp; &nbsp; // do NTIMES requests in go routines with waitgroupSize&nbsp; &nbsp; // do NTIMES requests sequentially&nbsp; &nbsp; timings_concurrent, total_concurrent := concurrentRequests(waitgroupSize)&nbsp; &nbsp; timings_sequential, total_sequential := sequentialRequests()&nbsp; &nbsp; return timingResult{&nbsp; &nbsp; &nbsp; &nbsp; WaitgroupSize:&nbsp; &nbsp; &nbsp; &nbsp;waitgroupSize,&nbsp; &nbsp; &nbsp; &nbsp; ConcurrentTimingsMs: timings_concurrent,&nbsp; &nbsp; &nbsp; &nbsp; ConcurrentTotalMs:&nbsp; &nbsp;total_concurrent,&nbsp; &nbsp; &nbsp; &nbsp; SequentialTimingsMs: timings_sequential,&nbsp; &nbsp; &nbsp; &nbsp; SequentialTotalMs:&nbsp; &nbsp;total_sequential,&nbsp; &nbsp; }}func persistTimings(timings timingResult, db *sql.DB) {&nbsp; &nbsp; persistRun(timings, db)&nbsp; &nbsp; currentRunId := getCurrentRunId(db)&nbsp; &nbsp; persistConcurrentTimings(currentRunId, timings, db)&nbsp; &nbsp; persistSequentialTimings(currentRunId, timings, db)}func concurrentRequests(waitgroupSize int) ([REQUESTS]int64, int64) {&nbsp; &nbsp; start := time.Now()&nbsp; &nbsp; var wg sync.WaitGroup&nbsp; &nbsp; var timings [REQUESTS]int64&nbsp; &nbsp; ch := make(chan int64, REQUESTS)&nbsp; &nbsp; for i := range timings {&nbsp; &nbsp; &nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; &nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; defer wg.Done()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; doGetChannel(URL, ch)&nbsp; &nbsp; &nbsp; &nbsp; }()&nbsp; &nbsp; &nbsp; &nbsp; // waitgroupsize is controlled using modulo&nbsp; &nbsp; &nbsp; &nbsp; // making sure experiment size is always NTIMES&nbsp; &nbsp; &nbsp; &nbsp; // independent of waitgroupsize&nbsp; &nbsp; &nbsp; &nbsp; if i%waitgroupSize == 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; close(ch)&nbsp; &nbsp; count := 0&nbsp; &nbsp; for ret := range ch {&nbsp; &nbsp; &nbsp; &nbsp; timings[count] = ret&nbsp; &nbsp; &nbsp; &nbsp; count++&nbsp; &nbsp; }&nbsp; &nbsp; return timings, time.Since(start).Milliseconds()}func doGetChannel(address string, channel chan int64) {&nbsp; &nbsp; // time get request and send to channel&nbsp; &nbsp; startSub := time.Now().UnixMilli()&nbsp; &nbsp; _, err := http.Get(address)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }&nbsp; &nbsp; stopSub := time.Now().UnixMilli()&nbsp; &nbsp; delta := stopSub - startSub&nbsp; &nbsp; channel <- delta}func sequentialRequests() ([REQUESTS]int64, int64) {&nbsp; &nbsp; startGo := time.Now()&nbsp; &nbsp; var timings_sequential [REQUESTS]int64&nbsp; &nbsp; for i := range timings_sequential {&nbsp; &nbsp; &nbsp; &nbsp; timings_sequential[i] = doGetReturn(URL)&nbsp; &nbsp; }&nbsp; &nbsp; return timings_sequential, time.Since(startGo).Milliseconds()}func doGetReturn(address string) int64 {&nbsp; &nbsp; // time get request without a waitgroup/channel&nbsp; &nbsp; start := time.Now()&nbsp; &nbsp; _, err := http.Get(address)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }&nbsp; &nbsp; duration := time.Since(start).Milliseconds()&nbsp; &nbsp; return duration}//// DBfunc setupDb() *sql.DB {&nbsp; &nbsp; //&nbsp; &nbsp; &nbsp; __________________________runs____________________&nbsp; &nbsp; //&nbsp; &nbsp; &nbsp;|&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; |&nbsp; &nbsp; // concurrent_timings(fk: run_id)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sequential_timings(fk: run_id)&nbsp; &nbsp; //&nbsp; &nbsp; const createRuns string = `&nbsp; &nbsp; CREATE TABLE IF NOT EXISTS runs (&nbsp; &nbsp; run_id INTEGER NOT NULL PRIMARY KEY,&nbsp; &nbsp; time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,&nbsp; &nbsp; waitgroup_size INTEGER,&nbsp; &nbsp; concurrent_total_ms INTEGER,&nbsp; &nbsp; sequential_total_ms INTEGER,&nbsp; &nbsp; concurrent_sequential_ratio REAL&nbsp; &nbsp; );`&nbsp; &nbsp; const createSequentialTimings string = `&nbsp; &nbsp; CREATE TABLE IF NOT EXISTS sequential_timings (&nbsp; &nbsp; run INTEGER,&nbsp; &nbsp; call_number INTEGER,&nbsp; &nbsp; timing_ms INTEGER,&nbsp; &nbsp; FOREIGN KEY(run) REFERENCES runs(run_id)&nbsp; &nbsp; );`&nbsp; &nbsp; const createConcurrentTimings string = `&nbsp; &nbsp; CREATE TABLE IF NOT EXISTS concurrent_timings (&nbsp; &nbsp; run INTEGER,&nbsp; &nbsp; channel_position INTEGER,&nbsp; &nbsp; timing_ms INTEGER,&nbsp; &nbsp; FOREIGN KEY(run) REFERENCES runs(run_id)&nbsp; &nbsp; );`&nbsp; &nbsp; // retrieve platform appropriate connection string&nbsp; &nbsp; dbString := getConnectionString(DBNAME)&nbsp; &nbsp; db, err := sql.Open("sqlite3", dbString)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }&nbsp; &nbsp; if _, err := db.Exec(createRuns); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }&nbsp; &nbsp; if _, err := db.Exec(createSequentialTimings); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }&nbsp; &nbsp; if _, err := db.Exec(createConcurrentTimings); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }&nbsp; &nbsp; return db}func getConnectionString(dbName string) string {&nbsp; &nbsp; // Generate platform appropriate connection string&nbsp; &nbsp; // the db is placed in the same directory as the current executable&nbsp; &nbsp; // retrieve the path to the currently executed executable&nbsp; &nbsp; ex, err := os.Executable()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; // retrieve path to containing dir&nbsp; &nbsp; dbDir := filepath.Dir(ex)&nbsp; &nbsp; // Append platform appropriate separator and dbName&nbsp; &nbsp; if runtime.GOOS == "windows" {&nbsp; &nbsp; &nbsp; &nbsp; dbDir = dbDir + "\\" + dbName&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; dbDir = dbDir + "/" + dbName&nbsp; &nbsp; }&nbsp; &nbsp; return dbDir}func persistRun(timings timingResult, db *sql.DB) {&nbsp; &nbsp; tx, err := db.Begin()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }&nbsp; &nbsp; insertRun, err := db.Prepare(`INSERT INTO runs(&nbsp; &nbsp; &nbsp; &nbsp; waitgroup_size,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; sequential_total_ms,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; concurrent_total_ms,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; concurrent_sequential_ratio)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; VALUES(?, ?, ?, ?)`)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }&nbsp; &nbsp; defer tx.Stmt(insertRun).Close()&nbsp; &nbsp; _, err = tx.Stmt(insertRun).Exec(&nbsp; &nbsp; &nbsp; &nbsp; timings.WaitgroupSize,&nbsp; &nbsp; &nbsp; &nbsp; timings.SequentialTotalMs,&nbsp; &nbsp; &nbsp; &nbsp; timings.ConcurrentTotalMs,&nbsp; &nbsp; &nbsp; &nbsp; float32(timings.ConcurrentTotalMs)/float32(timings.SequentialTotalMs),&nbsp; &nbsp; )&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }&nbsp; &nbsp; err = tx.Commit()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }}func getCurrentRunId(db *sql.DB) int {&nbsp; &nbsp; rows, err := db.Query("SELECT MAX(run_id) FROM runs")&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }&nbsp; &nbsp; var run_id int&nbsp; &nbsp; for rows.Next() {&nbsp; &nbsp; &nbsp; &nbsp; err = rows.Scan(&run_id)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; rows.Close()&nbsp; &nbsp; return run_id}func persistConcurrentTimings(runId int, timings timingResult, db *sql.DB) {&nbsp; &nbsp; tx, err := db.Begin()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }&nbsp; &nbsp; insertTiming, err := db.Prepare(`INSERT INTO concurrent_timings(&nbsp; &nbsp; &nbsp; &nbsp; run,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; channel_position,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; timing_ms)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; VALUES(?, ?, ?)`)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }&nbsp; &nbsp; for i, timing := range timings.ConcurrentTimingsMs {&nbsp; &nbsp; &nbsp; &nbsp; _, err = tx.Stmt(insertTiming).Exec(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; runId,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; timing,&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; err = tx.Commit()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }}func persistSequentialTimings(runId int, timings timingResult, db *sql.DB) {&nbsp; &nbsp; tx, err := db.Begin()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }&nbsp; &nbsp; insertTiming, err := db.Prepare(`INSERT INTO sequential_timings(&nbsp; &nbsp; &nbsp; &nbsp; run,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; call_number,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; timing_ms)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; VALUES(?, ?, ?)`)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }&nbsp; &nbsp; for i, timing := range timings.SequentialTimingsMs {&nbsp; &nbsp; &nbsp; &nbsp; _, err = tx.Stmt(insertTiming).Exec(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; runId,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; timing,&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; err = tx.Commit()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Go
我要回答