Rust Study #3

bepo·2022년 12월 11일

Rust

목록 보기
3/3

백준 풀면서 빠르게 수행하는 팁을 모아보자

단계별 풀고, 다른 사람 코드 보면서 꿀팁 모으는 중

방법 생각중

높은 랭커 사람의 코드를 읽으면서, 뭐 쓰는지 다 파악해볼까?
이게 수행시간 / 메모리 줄이는 거는 어느정도 편법이 있는 것 같음
수행시간도 입력값 읽어들일때 시간이 다소 소요되는 것 같고
utilforever 라는 사람꺼 코드 다 보고 싶긴 한데
https://mesajang.tistory.com/tag/%EB%B0%B1%EC%A4%80?page=5
여기부터 시작하면 좋을 것 같네, manybirds 라는 백준 네임드가 rust 코드 짠것들 모음
https://github.com/xCrypt0r/Baekjoon 이것도

몇몇 팁들

rust에 여러가지 기능을 쓰기 위해서 cargo new {name} 으로 하는 것이 좋다.
기능 추가할때마다 cargo.toml에 뭐 넣어야하는데 (makefile처럼) 간편해짐.
https://gist.github.com/jFransham/369a86eff00e5f280ed25121454acec1#number-one-optimization-tip-dont

프로파일링

Stack 메모리 사용하면 더 적게 쓴다고 함
valgrind 써서 메모리 leak 같은 것을 확인 가능 ok
sudo perf record -F 99 -a -g -- ./main < input
sudo mv perf.data ../../FlameGraph/
sudo perf script | ./stackcollapse-perf.pl | ./flamegraph.pl > flamegraph.svg
flamegraph.svg 보는것으로 확인은 가능한데, 이거는 굉장히 별로인듯.. ㅇㅇ
linux 위에 돌아가는 모든 프로그램이 다 측정됨, 뭐가 뭔지 안보여

pprof-rs 사용해서 profiling은 했는데, 이게 아주 작은 사이즈에서는 안되는건가

연산 시간 줄이는 법

몰?루
입력 / 출력할 때 공을 많이 들일 필요가 있다고 함

입력 받는 법

use std::io;
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).unwrap();
    let input: Vec<i32> = buffer.split_whitespace()
                          .map(|f| {f.parse().unwrap()})
                          .collect();
use std::io::{stdin, Read};
use std::fmt::Write;
use std::error::Error;

fn main () -> Result<(), Box<dyn Error>> {
    let mut input = String::new();
    stdin().read_to_string(&mut input)?;
    
    let mut values = input.split_ascii_whitespace().map(|s| s.parse::<i32>()).flatten();
    let n = values.next().unwrap();

    let mut result = String::new();
    for _ in 0..n {
        let a = values.next().unwrap();
        let b = values.next().unwrap();
        writeln!(result, "{}", a + b)?;
    }

    println!("{result}");
    Ok(())
}

위 방식처럼, 결과값을 어디에 모두 적어놨다가 한번에 print하는게 훨씬 빠른것 같아

위 메서드 차례대로

.read_line은 한줄 읽는거겠고
.unwrap()은 Err variant일 시에 panic! 매크로를 호출함
.split_whitespace()는 공백을 기준으로 split 하는 거고
.map()은 아직 모르겠으..
.parse()는 하나씩 뭔가 parsing하는 것 같고
.collect()는 하나의 리스트 형태로 만드는 거이려나?

profile
Dugu Dibap

0개의 댓글