[swift-users] Compilation time problems when building matrices

Elia Cereda eliacereda at gmail.com
Wed Jun 28 12:51:02 CDT 2017


Hi,

I currently writing a demo app to teach myself the fundamentals of Metal and a big part of that is obviously working with matrices. What I’m seeing is that the code build them has some serious compilation time problems.

The worst case is this function, which according to -debug-time-function-bodies takes over 9500ms of time to compile.

static func frustum(l: Float, r: Float, t: Float, b: Float, n: Float, f: Float) -> float4x4 {
    return float4x4(rows: [
        [ 2 * n / (r - l),                   0,  (r + l) / (r - l),                    0 ],
        [               0,     2 * n / (t - b),  (t + b) / (t - b),                    0 ],
        [               0,                   0, -(f + n) / (f - n), -2 * f * n / (f - n) ],
        [               0,                   0,                 -1,                    1 ],
    ])
}

I’ve tried making some naive changes to the code and gotten it down to a much more reasonable 4ms, but the result is not something I would write if given a choice.

static func frustum(l: Float, r: Float, t: Float, b: Float, n: Float, f: Float) -> float4x4 {
    let twoN = 2 * n
    
    let rPlusL = r + l
    let rMinusL = r - l
    
    let tPlusB = t + b
    let tMinusB = t - b
    
    let fPlusN = f + n
    let fMinusN = f - n
    
    return float4x4(rows: [
        [ twoN / rMinusL,              0,  rPlusL / rMinusL,                   0 ],
        [              0, twoN / tMinusB,  tPlusB / tMinusB,                   0 ],
        [              0,              0, -fPlusN / fMinusN, -twoN * f / fMinusN ],
        [              0,              0,                -1,                   1 ],
    ])
}

I’m taking this to swift-users since I’m aware this is a known pain point with the compiler. Is this specific instance something that would be worth filing a bug for?

Since I do not understand enough of the compiler to understand specifically what is causing problems with the first piece of code, I would also be extremely grateful if something from the core team (or anyone for that matter) could share some wisdom regarding what to do here.

Specifically, is there something that could be done to the first code to reduce the amount of overloads that the compiler needs to consider? In my naive view of the world, a sum or a multiplication between two Floats can only ever produce another Float, is there some way to pass this knowledge to the compiler?

Regards,
Elia Cereda

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170628/60a523d9/attachment.html>


More information about the swift-users mailing list