Golang 中 http.Get 的耗时比 curl 耗时大很多是什么原因?

2018-12-05 16:49:17 +08:00
 rayhy

可能这个问题比较小白,大家轻喷

我用 Golang 中http库的Get函数写个简单的下载网页的工具,发现下载网页时间很长,比 curl 长很多:

Golang 代码:


// Fetch prints the content found at a URL.
package main

import (
	"time"
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
)

func main() {

	for _, url := range os.Args[1:] {
		start := time.Now()
		if !(strings.HasPrefix(url, "https://") || strings.HasPrefix(url, "http://")) {
			url = "http://" + url
		}

		resp, err := http.Get(url)
		if err != nil {
			fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
			os.Exit(1)
		}
		fmt.Printf("[\033[0;31m%d\033[0m] %v\n", resp.StatusCode, resp.Request.URL)

		// Test download cost.
		//fmt.Println("Download cost:", time.Since(start))

		if _, err := io.Copy(os.Stdout, resp.Body); err != nil {
			fmt.Fprintf(os.Stderr, "\033[0;31mERROR\033[0m %v\n", err)
			os.Exit(1)
		}
		fmt.Println("Total cost:", time.Since(start))
	}
}

看到这么大的差距,我以为是io.Copy可能出了点问题,就在io.Copy前添了一个时间测试,结果:

Download cost: 21.651425s
Total cost: 21.656501s

可以看到时间主要是花在http.Get这里了。

我多次测试后都可以复现(包含测试不同网站),Google 也没有什么结果,搜索关键词都不知道怎么设置。。

这究竟是啥原因啊?

7747 次点击
所在节点    Go 编程语言
25 条回复
webluoye
2018-12-06 09:32:31 +08:00
涨知识
coolmenu
2018-12-06 09:42:05 +08:00
大概猜到 dns 解析的问题,不过细节却是不知道,涨知识了
js2854
2018-12-06 13:12:11 +08:00
歪个楼,查看程序运行时间用 time 命令就好了,不需要取开始时间结束时间相减
rayhy
2018-12-06 16:00:14 +08:00
@js2854,谢谢,又发现了一个新命令。我试了一下,`/usr/bin/time -p`更适合我这个情况。
rayhy
2018-12-07 08:49:49 +08:00
又开了个帖子解释了下为啥 go dns 查询这么慢
https://www.v2ex.com/t/515096#reply1

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/514632

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX