File: parallel_requests.rs

package info (click to toggle)
rust-isahc 1.7.2%2Bds-33
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,184 kB
  • sloc: makefile: 26; sh: 1
file content (45 lines) | stat: -rw-r--r-- 1,343 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//! In this example, we demonstrate Isahc's ability to run many requests
//! simultaneously with no extra cost. Concurrent requests may be made in the
//! same thread, or from different threads as in this example.
//!
//! We're using [rayon] here to make parallelism easy.
//!
//! [rayon]: https://github.com/rayon-rs/rayon

use isahc::HttpClient;
use rayon::prelude::*;
use std::{env, time::Instant};

fn main() -> Result<(), isahc::Error> {
    let count = env::args()
        .nth(1)
        .and_then(|s| s.parse::<u32>().ok())
        .unwrap_or(100);

    let urls: Vec<String> = (0..count)
        .map(|i| format!("https://httpbin.org/anything/{:03}", i))
        .collect();
    let client = HttpClient::new()?;

    let start = Instant::now();

    // Iterate over each URL and send a request in parallel.
    urls.par_iter()
        .try_for_each(|url| {
            let start = Instant::now();
            let response = client.get(url)?;
            let end = Instant::now();
            println!(
                "{}: {} in {:?}",
                &url,
                response.status(),
                end.duration_since(start)
            );

            Ok(())
        })
        .map(|_| {
            let end = Instant::now();
            println!("Ran {} requests in {:?}", count, end.duration_since(start));
        })
}