BLOG

Notes from the KAYAC hyper-casual team

Visualizing Compile Time in Unity

Takashi Hirayama

The compile timer window

In Unity, you don't have to wait for a build to try out your game. As soon as the source code compiles, you can run it.

But as the amount of code grows, even that wait becomes unbearable.

I'm Hirayama from the Technology Department, and in this article I'll write about how I visualized compile time. I also looked into how slow compilation actually gets for a given amount of code.

First, measure it

You can tell whether Unity is compiling from EditorApplication.isCompiling. After that, all you need is a quick-and-dirty editor window to display it.

public class CompileTimer : EditorWindow
{
    [MenuItem("Kayac/CompileTimer")]
    static void Init()
    {
        EditorWindow window = GetWindowWithRect(typeof(CompileTimer), new Rect(0, 0, 200f, 100f));
        window.Show();
    }

    // Variables can't be kept across a compile, so they have to go into EditorPrefs
    const string compileStartTimeKey = "kayac_compileStartTime";
    const string lastCompileTimeKey = "kayac_lastCompileTime";

    void OnGUI()
    {
        DateTime startTime = new DateTime();
        var compiling = EditorApplication.isCompiling;
        bool prevCompiling = false;
        if (EditorPrefs.HasKey(compileStartTimeKey))
        {
            string str = EditorPrefs.GetString(compileStartTimeKey);
            if (!String.IsNullOrEmpty(str))
            {
                startTime = DateTime.Parse(str);
                prevCompiling = true;
            }
        }
        float lastTime = 0f;
        lastTime = EditorPrefs.GetFloat(lastCompileTimeKey);
        var currentTime = 0f;
        if (prevCompiling)
        {
            if (compiling)
            {
                currentTime = (float)(DateTime.Now - startTime).TotalSeconds;
            }
            else
            {
                lastTime = (float)(DateTime.Now - startTime).TotalSeconds;
                EditorPrefs.SetFloat(lastCompileTimeKey, lastTime);
                EditorPrefs.DeleteKey(compileStartTimeKey);
            }
        }
        else if (compiling)
        {
            EditorPrefs.SetString(compileStartTimeKey, DateTime.Now.ToString());
        }
        else if (EditorPrefs.HasKey(compileStartTimeKey))
        {
            EditorPrefs.DeleteKey(compileStartTimeKey);
        }
        EditorGUILayout.LabelField("Compiling:", compiling ? currentTime.ToString("F2") : "No");
        EditorGUILayout.LabelField("LastCompileTime:", lastTime.ToString("F2"));
        this.Repaint();
    }
}

The code is on GitHub along with the whole project. Every time OnGUI is called, it checks isCompiling and treats "was compiling last time, isn't compiling now" as the end of compilation. It saves the start time and subtracts it from the current time to get the duration.

The code is this long for such a simple job because variables don't survive a compile. Even if you keep a variable like _compileStartTime, the class instance is recreated when compilation finishes, and the value turns into "January 1, year 1." That's why everything that needs to persist is saved to EditorPrefs.

I don't like that ToString() triggers a GC Alloc just for OnGUI, but I'll think about that some other time (caching the values for as long as the variables survive should do it).

And with that, I had an editor extension that shows how long the last compile took and, as in the image at the top of this article, the elapsed time while a compile is running.

What makes compilation slow

The short answer: simply the amount of code. I tried all sorts of things, such as the number of relationships between classes, or partial classes, but none of them seems to matter much.

For example, the sample project I made for this article compiles in 4 to 6 seconds. It has next to no code compared with a shipping game, but it seems compilation always takes at least this long. I measured on a MacBook Pro Mid-2014.

If I add 1,000 classes with 1,000 methods each, generated with the script I wrote for this article (GenerateHuge), the code comes to about a million lines and compilation takes around 65 seconds. At that point, things get pretty painful. Every time you slip in a Debug.Log and run again, you wait a whole minute.

The ideal solution is probably to add content as data that can go into AssetBundles rather than as code, wherever possible. I think it matters a great deal whether you can set up that kind of pipeline before full-scale content production begins. If you neglect it, the code creeps up little by little, and by the time you notice, it's too late. This visualization tool might help prevent that. If I can, I'd like to change it so it shows the time without opening a dedicated window.

Of course, there are ways to deal with code that already exists, such as splitting into DLLs (2017.3 and later) and putting code under Plugins. If you've passed a million lines and it really hurts, you'll need to make full use of these.

Still, I'd rather take action before it gets to that point.

Bonus

While I was at it, I also added a feature that measures the amount of code in the project and shows how much of it is under each folder. There's a "コード量分析" (code amount analysis) button,

The compile timer window with the code amount analysis button

and pressing it generates codeAmount.txt next to the Assets folder. For an example, take a look at the results for our Tokyo Prison. The unit is bytes, which you can think of as roughly the number of characters. Try comparing it with your own product.

By the way, Tokyo Prison has a fair amount of auto-generated code. For example, quite a lot of it was generated by conversion from After Effects, which is bad in terms of compile time. For animations that simply play and finish, I'd like to avoid implementing them in code as much as possible.