iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
💠

Comparing Function Memory Usage in F#

に公開

By using .NET's GC.GetTotalMemory, you can retrieve the memory usage on .NET in bytes.

open System
let memory = GC.GetTotalMemory false
// val memory: int64 = 94499104L

You can estimate a function's memory usage by comparing this memory usage before and after the function call.

let before = GC.GetTotalMemory false
f () // Call some function
let after = GC.GetTotalMemory false
let memory = after - before
// val memory: int64 = Memory usage in bytes

You can define and reuse a function that takes a function as a parameter to measure its memory usage.

let measureMemoryUsage (f: unit -> unit) =
    let before = GC.GetTotalMemory false
    f ()
    let after = GC.GetTotalMemory false
    after - before

The following is a program that compares the memory usage between a function that calculates the greatest common divisor (GCD) using unfold (gcd) and a function that uses a loop (gcd_while).

open System

let gcd u v =
    Seq.unfold
        (fun (x, y) ->
            if y = 0 then
                None
            else
                Some((x, y), (y, x % y)))
        (u, v)
    |> Seq.last
    |> snd

let gcd_while u v =
    let mutable x = u
    let mutable y = v
    let mutable t = 0

    while x > 0 do
        if x < y then
            t <- x
            x <- y
            y <- t

        x <- x - y

    y

let measureMemoryUsage (f: unit -> unit) =
    let before = GC.GetTotalMemory(true)
    f ()
    let after = GC.GetTotalMemory(true)
    after - before

let function1 () = printfn "%d" (gcd 461952 116298)
let function2 () = printfn "%d" (gcd_while 461952 116298)

let memoryUsage1 = measureMemoryUsage function1
let memoryUsage2 = measureMemoryUsage function2

printfn "Function 1 used %d bytes" memoryUsage1
printfn "Function 2 used %d bytes" memoryUsage2
18
18
Function 1 used 1184 bytes
Function 2 used 152 bytes

We can see that the calculation using unfold results in higher memory usage.

Discussion