mirror of
https://github.com/NotAShelf/tct.git
synced 2024-11-22 13:20:49 +00:00
71 lines
1.4 KiB
Go
71 lines
1.4 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"flag"
|
||
|
"fmt"
|
||
|
"net/http"
|
||
|
"os"
|
||
|
"os/signal"
|
||
|
"sync"
|
||
|
"syscall"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
func main() {
|
||
|
urlPtr := flag.String("url", "http://example.com", "URL to fetch")
|
||
|
maxRequestsPtr := flag.Int("max", 100, "Maximum number of parallel requests")
|
||
|
delayPtr := flag.Duration("delay", 0, "Delay between requests")
|
||
|
|
||
|
flag.Parse()
|
||
|
url := *urlPtr
|
||
|
maxRequests := *maxRequestsPtr
|
||
|
delay := *delayPtr
|
||
|
|
||
|
// context that listens for the interrupt signal.
|
||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||
|
defer stop()
|
||
|
|
||
|
optimal := 0
|
||
|
minTime := time.Duration(0)
|
||
|
for i := 1; i <= maxRequests; i++ {
|
||
|
// check for cancellation before starting the loop
|
||
|
if ctx.Err() != nil {
|
||
|
break
|
||
|
}
|
||
|
start := time.Now()
|
||
|
wg := &sync.WaitGroup{}
|
||
|
wg.Add(i)
|
||
|
for j := 0; j < i; j++ {
|
||
|
go func() {
|
||
|
defer wg.Done()
|
||
|
select {
|
||
|
case <-ctx.Done():
|
||
|
fmt.Println("Operation cancelled.")
|
||
|
return
|
||
|
default:
|
||
|
time.Sleep(delay)
|
||
|
makeRequest(url)
|
||
|
}
|
||
|
}()
|
||
|
}
|
||
|
wg.Wait()
|
||
|
duration := time.Since(start)
|
||
|
fmt.Printf("Parallel Requests: %d, Time Taken: %s\n", i, duration)
|
||
|
if minTime == 0 || duration < minTime {
|
||
|
minTime = duration
|
||
|
optimal = i
|
||
|
}
|
||
|
}
|
||
|
fmt.Printf("\nOptimal Number of Parallel TCP Requests: %d\n", optimal)
|
||
|
}
|
||
|
|
||
|
func makeRequest(url string) {
|
||
|
resp, err := http.Get(url)
|
||
|
if err != nil {
|
||
|
fmt.Println(err)
|
||
|
return
|
||
|
}
|
||
|
defer resp.Body.Close()
|
||
|
}
|