Profiling



  • Disclaimer: I did not program with javascript until started playing screeps.

    Recently my script has been terminated due to CPU limit. In order to deal with this issue I wrote the following code:

    var enable_profiling = true;
    if (enable_profiling) {
        Memory.p = Memory.p || {};
    
        var wrap = function(c, n) {
            var p = Memory.p[n] || { usage: 0, count: 0 };
            Memory.p[n] = p;
    
            var f = c.prototype[n];
            c.prototype[n] = function() {
                var ts = Game.getUsedCpu();
                var rc = f.apply(this, arguments);
                p.usage += Game.getUsedCpu() - ts;
                ++p.count;
                return rc;
            };
        };
    
        wrap(RoomPosition, 'isNearTo');
        wrap(RoomPosition, 'findPathTo');
        wrap(RoomPosition, 'isEqualTo');
        wrap(RoomPosition, 'findClosest');
        wrap(Creep, 'moveByPath');
        wrap(Creep, 'moveTo');
        wrap(Creep, 'pickup');
        wrap(Creep, 'build');
        wrap(Creep, 'repair');
        wrap(Creep, 'harvest');
        wrap(Creep, 'upgradeController');
        wrap(Room, 'lookForAt');
        wrap(Room, 'find');
        wrap(Spawn, 'createCreep');
    }
    
    ....   // main code
    
    var report_interval = 200;
    if (Game.time % report_interval == 0) {
            var summary = 0;
            for (var n in Memory.p) {
                var p = Memory.p[n];
                if (p.count === 0) {
                    p.average = 0;
                    continue;
                }
                p.average = p.usage / p.count;
                summary += p.average;
            }
    
            for (var n in Memory.p) {
                var p = Memory.p[n];
                console.log(n + ': ' + p.usage.toFixed(2) + '/' + p.count + ' == ' + p.average.toFixed(2)
                            + ' (' + (p.average * 100 / summary).toFixed(2) + '%)');
            }
            console.log('--- ' + summary.toFixed(2));
    
            Memory.p = {};
    }
    

    Feel free to use it.



  • Piggy backing on this, I just released my profiler as OS. https://github.com/gdborton/screeps-profiler