Advertisement
Guest User

Untitled

a guest
Nov 21st, 2022
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.16 KB | Source Code | 0 0
  1. use std::time::Instant;
  2.  
  3. fn get_char_by_bytes(val: &String, index: usize) -> char {
  4.     val.as_bytes()[index] as char
  5. }
  6.  
  7. fn get_nth_character(val: &String, index: usize) -> char {
  8.     val.chars().nth(index).unwrap()
  9. }
  10.  
  11. fn main() {
  12.     let word = String::from("Hello world").repeat(1000);
  13.     // let index = 10usize;
  14.     // let answer = 'o';
  15.     let time_limits = (3..=7).map(|x| 10u32.pow(x));
  16.     let time_limit = time_limits.into_iter().nth(0).unwrap();
  17.     for index in 990..1000 {
  18.         println!("For iteration {}, index {}", time_limit, index);
  19.         let now = Instant::now();
  20.         for _ in 0..time_limit {
  21.             get_char_by_bytes(&word, index);
  22.         }
  23.         let elapsed = now.elapsed();
  24.         println!("Elapsed time for bytes {:2?}", elapsed);
  25.  
  26.         let now = Instant::now();
  27.         for _ in 0..time_limit {
  28.             get_nth_character(&word, index);
  29.         }
  30.         let elapsed2 = now.elapsed();
  31.         println!("Elapsed time for nth character {:2?}", elapsed2);
  32.  
  33.         println!(
  34.             "Ratio of slowdown {:.2}",
  35.             ((elapsed2.as_micros() as f64) / (elapsed.as_micros() as f64))
  36.         );
  37.     }
  38. }
  39.  
Tags: rust strings
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement