summaryrefslogtreecommitdiff
path: root/bin/measure_mem.sh
blob: 9839815bb3ee0e965efe51fe81c3b72861159567 (plain)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/bin/sh -e

YEAR="${YEAR:-$(date +%Y)}"
DAY="${DAY:-$(TZ=EST date '+%d')}"
IMPL="${IMPL:-rust}"
PARTS="${AOC_PARTS:-1 2}"

ITERS="${ITERS:-10}"
MODE="${MODE:-valgrind}"

cd "${YEAR}/${IMPL}/day${DAY}"
case "${IMPL}" in
  'rust')
    cargo build --release
    EXECUTABLE="../target/release/day${DAY}"
    ;;
  *)
    echo "Unknown implementation: ${IMPL}" >&2
    exit
    ;;
esac

# https://stackoverflow.com/q/774556/peak-memory-usage-of-a--process
for PART in $(echo ${PARTS})
do
  export AOC_PARTS="${PART}"

  OUT="memmax-${YEAR}-${IMPL}-${DAY}-${PART}.txt"
  case "${MODE}" in
    'valgrind')
      valgrind --tool=massif --pages-as-heap=yes \
          --massif-out-file=massif.out \
          "${EXECUTABLE}" "${@}"
      grep mem_heap_B massif.out | \
          sed -e 's/mem_heap_B=\(.*\)/\1/' | sort -g | tail -n 1 \
          >"${OUT}"
      MEM=$(cat "${OUT}")
      printf "${YEAR}-${IMPL}-${DAY}-${PART}: MEM: ${MEM} %dk %dM\n" \
          $(( MEM / 1024 )) $(( MEM / 1024 / 1024 ))
      ;;
    'time')
      # %X The average amount in (shared) text space used in kilobytes.
      # %D The average amount in (unshared) data/stack space used in kilobytes.
      # %K The total space used (%X+%D) in kilobytes.
      # %M The maximum memory the process had in use at any time in kilobytes.
      export TIMEFMT='%M'
      for I in $(seq "${ITERS}"); do
        zsh -c time "${EXECUTABLE}" "${@}" 2>&1 >/dev/null | tail -1
      done >"${OUT}"

      ALL_MEMORY_USAGES="$(cat "${OUT}" )"
      NO_OF_ITERS=$(echo "${ALL_MEMORY_USAGES}" | wc -l)
      ARITHM="$(echo "( ${ALL_MEMORY_USAGES}" | tr '\n' '+'; \
          echo "0 ) / ${NO_OF_ITERS}" )"
      MEAN_MEMORY=$(( $(echo ${ARITHM}) ))

      echo "${YEAR}-${IMPL}-${DAY}-${PART}: Mean: ${MEAN_MEMORY}kB"
      echo "${YEAR}-${IMPL}-${DAY}-${PART}: Mean: ${MEAN_MEMORY}kB" >>"${OUT}"
      ;;
    *)
      echo "Unkown mode ${MODE}" >&2
      ;;
  esac
done