namemkazaza

Кто быстрее ? Гугл / Яндекс

Jun 2nd, 2020
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.74 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "io/ioutil"
  6.     "net/http"
  7. )
  8.  
  9. func fetchSite(url string) (string, error) {
  10.     resp, err := http.Get(url)
  11.     defer resp.Body.Close()
  12.     data, err  := ioutil.ReadAll(resp.Body)
  13.     if err != nil {
  14.         return "", err
  15.     }
  16.     return string(data), nil
  17. }
  18.  
  19. func fetchGoogle(q string) string {
  20.     var result string
  21.     var err error
  22.     func() {
  23.         result, err = fetchSite("https://www.google.com/search?q=" + q)
  24.     }()
  25.     if err != nil {
  26.         return "Error"
  27.     }
  28.     return "Google"
  29. }
  30.  
  31. func fetchYandex(q string) string {
  32.     var result string
  33.     var err error
  34.     func() {
  35.         result, err = fetchSite("https://yandex.ru/search/?text=" + q)
  36.     }()
  37.     if err != nil {
  38.         return "Error"
  39.     }
  40.     return "Yandex"
  41. }
  42.  
  43. func main() {
  44.     var i int
  45.     var yCounter int
  46.     var gCounter int
  47.     var tests int
  48.     respGoogle := make(chan bool)
  49.     respYandex := make(chan bool)
  50.  
  51.     fmt.Print("Tests to perform: ")
  52.     fmt.Scan(&tests)
  53.  
  54.     for i=1; i <= tests; i++ {
  55.         go func() {
  56.             if fetchYandex("test") != ""{
  57.                 respYandex <- true
  58.             } else {
  59.                 fmt.Println("An error occurred with Yandex")
  60.             }
  61.         }()
  62.  
  63.         go func() {
  64.             if fetchGoogle("test") != ""{
  65.                 respGoogle <- true
  66.             } else {
  67.                 fmt.Println("An error occurred with Google")
  68.             }
  69.         }()
  70.  
  71.         select {
  72.         case <- respGoogle:
  73.             gCounter += 1
  74.             fmt.Printf("Test %d: Google was faster\n", i)
  75.         case <- respYandex:
  76.             yCounter += 1
  77.             fmt.Printf("Test %d: Yandex was faster\n", i)
  78.         }
  79.     }
  80.     fmt.Printf("By the results of %d tests, ", i-1)
  81.     if gCounter > yCounter{
  82.         fmt.Printf("Google was faster (%d vs. %d)\n", gCounter, yCounter)
  83.     } else if yCounter > gCounter {
  84.         fmt.Printf("Yandex was faster (%d vs. %d)\n", yCounter, gCounter)
  85.     } else {
  86.         fmt.Printf("Google and Yandex showed the same performance")
  87.     }
  88. }
Add Comment
Please, Sign In to add comment