Chronomètre mesurant la durée d'une fonction

Description

Cette classe est un chronomètre qui vous permet de mesurer le temps que prend votre code. J'ai fait cette classe en me basant sur le framework Atlas.

Il y a une classe StopWatch qui est la base du chronomètre, vous n'avez pas à utiliser directement cette classe ! La seconde classe est un singleton, vous n'avez pas besoin de l'instancier pour l'utiliser.

Le fonctionnement est simple, avant de rentrer dans le code, vous démarrer un nouveau StopWatch, executer votre code et stopper le StopWatch.

Cyril.Debug.Analyzers.start('Test1');
// Le code a executé
Cyril.Debug.Analyzers.stop('Test1');

Une popup vous affichera le temps passer pour chacun des compteurs courant. Vous avez aussi les méthodes pause et resume qui font ce que le nom indique :-)

Source / Exemple :


Type.registerNamespace('Cyril.Debug');

Cyril.Debug.StopWatch = function(name, description){
    /// <summary>This class can mesure the time take by some line of code. You dont't have to manipulate this object directly, use the Cyril.Debug.Analyzers type.</summary>
    /// <param name="name" type="String" mayBeNull="false">Name of this StopWatch.</param>
    /// <param name="description" type="String" optional="true" mayBeNull="true">Description of this StopWatch.</param>
    /// <returns type="StopWatch"></returns>
    var e = Function._validateParams(arguments, [
        {name: 'name', type: String},
        {name: 'description', type: String, mayBeNull: true, optional:true}
    ]);
    if (e) throw e;
    
    /* Private fields */
    this._name          = name; 
    this._description   = description || '';
}
Cyril.Debug.StopWatch.prototype = {
    
    /* Private fields" */
    _startDate : null, 
    _endDate : null,
    
    /* Public accesssors */
    get_name : function(){
      return this._name;  
    },
    
    get_description : function(){
        return this._description; 
    },
    set_description : function(description){
        this._description = description; 
    },
    
    _elapsedTime : 0, 
    get_elapsedTime : function(){
        return this._elapsedTime;
    },
    
    _isStarted : false, 
    get_isStarted : function(){
        return this._isStarted; 
    },
    _isRunning : false, 
    get_isRunning : function(){
        return this._isRunning; 
    },
    _isStopped : false, 
    get_isStopped : function() {
        return this._isStopped;
    },

    /* Public Methods */
    
    start : function(){
        this._isStarted = true; 
        this._isRunning = true;
        this._elapsedTime = 0;
        this._startDate = new Date(); 
    },
    pause : function(){
        this._elapsedTime += new Date() - this._startDate;
        this._isRunning = false;
    },
    resume : function(){
        this._isStarted = true; 
        this._startDate = new Date(); 
    },
    stop : function(){
        if(this._isRunning)
            this._elapsedTime += new Date() - this._startDate;
        this._isRunning = false;
        this._isStopped = true;
    }
}
Cyril.Debug.StopWatch.registerClass('Cyril.Debug.StopWatch', null);

Cyril.Debug._Analyzers = function(){
    /// <summary></summary>
}
Cyril.Debug._Analyzers.prototype = {
    
    /* Private fields */
    _popup : null,
    _stopWatches : {},
    
    /* Public properties */
    get_StopWatch : function(name){
        /// <summary>Get a StopWatch objet by name.</summary>
        /// <param name="name" type="String" mayBeNull="false" optional="false">Name of the StopWatch.</param>
        /// <returns type="StopWatch"></returns>
        var e = Function._validateParams(arguments, [
            {name: 'name', type: String, mayBeNull: false, optional: false},
            {name: 'description', type: String, mayBeNull: true, optional:true}
        ]);
        if (e) throw e;

        return this._stopWatches[name]; 
    },
    
    /* Public methods */
    
    start : function(name, description){
        /// <summary>Start a new StopWatch, if the name already existe it will be deleted.</summary>
        /// <param name="name" type="String" mayBeNull="false" optional="false">Name of the StopWatch.</param>
        /// <param name="description" type="String" optional="true" mayBeNull="true">Description of this StopWatch.</param>        
        var e = Function._validateParams(arguments, [
            {name: 'message', type: String, mayBeNull: false, optional: false}
        ]);
        if (e) throw e;

        this._stopWatches[name] = new Cyril.Debug.StopWatch(name, description);
        this._stopWatches[name].start();
    },
    pause : function(name){
        /// <summary>Pause the associated StopWatch, use the Resume method to restart it.</summary>
        /// <param name="name" type="String" mayBeNull="false" optional="false">Name of the StopWatch.</param>
        var e = Function._validateParams(arguments, [
            {name: 'message', type: String, mayBeNull: false, optional: false}
        ]);
        if (e) throw e;
    
        this._stopWatches[name].pause();
    },
    resume : function(name){
        /// <summary>Resume the associated StopWatch.</summary>
        /// <param name="name" type="String" mayBeNull="false" optional="false">Name of the StopWatch.</param>
        var e = Function._validateParams(arguments, [
            {name: 'message', type: String, mayBeNull: false, optional: false}
        ]);
        if (e) throw e;

        this._stopWatches[name].resume();
    },
    stop : function(name){
        /// <summary>Stop the associated StopWatch and display the results.</summary>
        /// <param name="name" type="String" mayBeNull="false" optional="false">Name of the StopWatch.</param>
        var e = Function._validateParams(arguments, [
            {name: 'message', type: String, mayBeNull: false, optional: false}
        ]);
        if (e) throw e;

        this._stopWatches[name].stop();
        this.display();
    }, 
    display : function(){
        /// <summary>Display all StopWatch in a popup.</summary>
        if (this._popup){
            try {
                this._popup.close(); 
            } catch (ex) {
            }
        }
        
        this._popup = window.open('about:blank', '_blank', 'resizable=yes,scrollbars=yes,width=300, height=200');
        if (!this._popup){
            alert('un anti popup a bloqué la fenêtre des résultats des tests');
            return;
        }
        var sb = new Sys.StringBuilder(); 
        sb.append('<html><head><title>Cyril.Debug.Analyzers</title></head><body><ul>');
        for (name in this._stopWatches){
            sb.append(String.format('<li><strong>{0}</strong> : {1} ms', this._stopWatches[name].get_name(), this._stopWatches[name].get_elapsedTime()));
            var description = this._stopWatches[name].get_description();
            if (description){
                sb.append(String.format('<br /><p>{0}</p>', description));
            }
            sb.append('</li>');
        }
        sb.append('</ul></body></html>');
        this._popup.document.write(sb.toString()); 
    }    
}
Cyril.Debug._Analyzers.registerClass('Cyril.Debug._Analyzers', null);

Cyril.Debug.Analyzers = new Cyril.Debug._Analyzers();

Conclusion :


Vous trouverez dans le zip un exemple d'utilisation de ce chronomètre, pour pouvoir l'executer il vous faut la beta 1 d'Atlas (http://ajax.asp.net) et Visual Web Dev Express (gratuit : http://www.microsoft.com/france/msdn/vstudio/express/vwd/telechargez.mspx)

Si vous ne voulez pas utiliser ASP.net pour tester le script il vous faudra utiliser Microsoft Ajax Library pour faire fonctionner le fichier JavaScript.

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.