Date Time Code
  Home arrow Date Time Code arrow Bs_StopWatch
Codewalker Forums 
  Tutorials  
Database Articles  
Miscellaneous  
Navigation Usability  
PEAR Articles  
Programming Basics  
Server Administration  
XML Tutorials  
  Reviews  
Database Book Reviews  
Linux Book Reviews  
Miscellaneous Reviews  
PHP Book Reviews  
PHP Software Reviews  
Server Admin Reviews  
SQL Tool Reviews  
  Code Gallery  
Content Management Code  
Contest Code  
Counters Code  
Database Code  
Date Time Code  
Discussion Board Code  
Email Code  
File Manipulation Code  
GUI Code  
Link Farm Code  
Miscellaneous Code  
Search Code  
Site Navigation Code  
User Management Code  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Download TestComplete 
Forums Sitemap 
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
DATE TIME CODE

Bs_StopWatch
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2002-11-27

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    class to measure time intervals in microseconds.
    You can take times during a code run and at the end get a time table as HTML or text table. The output will contain total and as delta between each take in microseconds.
    for a howto go to: http://www.blueshoes.org/howto/Bs_StopWatch.pdf


    By : blueshoes

    <?php
    define('BS_STOPWATCH_VERSION', '4.0.$x$');

    define ('BS_STOPWATCH_SW_SEC' , 1);
    define ('BS_STOPWATCH_SW_MSEC', 0);

    /*************************************************************************
    * Stopwatch - class to measure time intervals in microseconds.
    *
    * ... well... hey it's a stopwatch, what can I say more about it :-)
    * You can take times during a code run and at the end get a time table as
    * HTML or text table. The output will contain total and as delta between
    * each take in microseconds.
    *
    * NOTE: This class makes use of php's microtime(). from the manual:
    * "This function is only available on operating systems that support the
    * gettimeofday() system call."
    * I know that linux and windows do that. Haven't seen anything about other os.
    *
    * --sb This class is no more an extension from Bs_Object because I need it in Bs_Object
    * and I don't want any conflicts. I think we can do this with a basic object like this one.
    *
    * @author sam blum <sam at blueshoes dot org>
    * @copyright blueshoes.org, part of the php application framework
    * @version 4.2.$id$
    * @package util
    * @access public
    */
    class Bs_StopWatch {

    var $_startTime = NULL; // The start time.
    var $_stops = NULL; // Every call to takeTime() will add an entry to $_stops
    var $_lastTakeTime = NULL; // Last saved intermediate time
    var $_lastDeltaTime = NULL; // Last non saved intermediate time

    /**
    * Constructor.
    * @access public (pseudo static)
    */
    function Bs_StopWatch() {
    $this->reset();
    }

    /**
    * Resets the stopwatch.
    * @access public
    * @return void
    */
    function reset() {
    $this->_lastTakeTime = $this->_lastDeltaTime = $this->_startTime = explode(' ', microtime());
    $this->_stops = array();
    }

    /**
    * Takes a time and calculates the total time so far and the delta time
    * since the last take. These values are stored.
    * @access public
    * @param string $info Add any info as memo for what the time take stands for.
    * @return void
    */
    function takeTime($info='') {
    $now = explode(' ', microtime());
    $tot = (round( (($now[BS_STOPWATCH_SW_SEC] - $this->_startTime[BS_STOPWATCH_SW_SEC]) + ($now[BS_STOPWATCH_SW_MSEC] - $this->_startTime[BS_STOPWATCH_SW_MSEC]))*1000 ));
    $delta = (round( (($now[BS_STOPWATCH_SW_SEC] - $this->_lastTakeTime[BS_STOPWATCH_SW_SEC]) + ($now[BS_STOPWATCH_SW_MSEC] - $this->_lastTakeTime[BS_STOPWATCH_SW_MSEC]))*1000 ));
    $this->_lastTakeTime = $now;
    $this->_stops[] = array('INFO'=>$info, 'TOT'=>$tot, 'DELTA'=>$delta);
    }

    /**
    * Returns total time in ms since reset.
    * @access public
    * @return integer Total time in ms since reset.
    */
    function getTime() {
    $now = explode(' ', microtime());
    return (round( (($now[BS_STOPWATCH_SW_SEC] - $this->_startTime[BS_STOPWATCH_SW_SEC]) + ($now[BS_STOPWATCH_SW_MSEC] - $this->_startTime[BS_STOPWATCH_SW_MSEC]))*1000 ));
    }

    /**
    * Returns total time in ms since last call to getDelta()
    * @access public
    * @return integer Total time in ms since since last call.
    */
    function getDelta() {
    $now = explode(' ', microtime());
    $delta = (round( (($now[BS_STOPWATCH_SW_SEC] - $this->_lastDeltaTime[BS_STOPWATCH_SW_SEC]) + ($now[BS_STOPWATCH_SW_MSEC] - $this->_lastDeltaTime[BS_STOPWATCH_SW_MSEC]))*1000 ));
    $this->_lastDeltaTime = $now;
    return $delta;
    }

    /**
    * Displays all stops so far as HTML table.
    * @access public
    * @param string $title a title to display
    * @return string an html table
    */
    function toHtml($title='') {
    $ret = '';
    if ($title != '') $ret .= "<B>{$title}</B><br>";

    $this->_weightIt(); // Do some weighting

    $ret .= <<< EDO
    <table cellspacing="0" cellpadding="2">
    <tr>
    <th bgcolor="Aqua">Nr.</th>
    <th bgcolor="Silver">INFO</th>
    <th bgcolor="Aqua">DELTA<br>(ms)</th>
    <th bgcolor="Silver">TOT<br>(ms)</th>
    <th bgcolor="Aqua">-</th>
    </td>
    EDO;


    $stopSize = sizeOf($this->_stops);
    for ($i=0; $i<$stopSize; $i++) {
    $stop = $this->_stops[$i];
    $weight = str_pad('', $stop['weight'], '*');
    $ret .= <<< EDO
    <tr>
    <td align="center" bgcolor="Aqua">{$i}</td>
    <td bgcolor="Silver">{$stop['INFO']}</td>
    <td align="right" bgcolor="Aqua">{$stop['DELTA']}</td>
    <td align="right" bgcolor="Silver">{$stop['TOT']}</td>
    <td align="left" bgcolor="Aqua">{$weight}</td>
    </tr>
    EDO;
    }
    $ret .= "</table>";
    return $ret;
    }

    /**
    * Displays all stops so far as simple string table.
    * @access public
    * @param string $title a title to display
    * @return string table
    */
    function toString($title='') {
    $this->_weightIt(); // Do some weighting

    $padInfo = $padDelta = $padTot = 0;
    $stopSize = sizeOf($this->_stops);
    for ($i=0; $i<$stopSize; $i++) {
    $stop = $this->_stops[$i];
    $padInfo = max($padInfo, strlen($stop['INFO']));
    $padDelta = max($padDelta, strlen($stop['DELTA']));
    $padTot = max($padTot, strlen($stop['TOT']));
    }
    $padDelta++; $padTot++;

    $ret = '';
    $ret .= $title . "\n" . str_pad('', $padInfo, ' ', STR_PAD_LEFT);
    $ret .= '|' . str_pad('d', $padDelta, ' ', STR_PAD_BOTH);
    $ret .= '|' . str_pad('tot [ms]', $padTot, ' ', STR_PAD_BOTH);
    $ret .= "\n";
    $ret .= str_pad('', strlen($ret), '-') . "\n";
    for ($i=0; $i<$stopSize; $i++) {
    $stop = $this->_stops[$i];
    $ret .= str_pad($stop['INFO'], $padInfo, ' ', STR_PAD_LEFT);
    $ret .= '|' . str_pad($stop['DELTA'], $padDelta, ' ', STR_PAD_LEFT);
    $ret .= '|' . str_pad($stop['TOT'], $padTot, ' ', STR_PAD_LEFT);
    $ret .= ' |' . str_pad('', $stop['weight'], '*');
    $ret .= "\n";
    }
    return $ret;
    }

    function _weightIt() {
    // Do some weighting
    $stopSize = sizeOf($this->_stops);
    if ($stopSize<=0) return; // no data
    $totalTime = $this->_stops[$stopSize-1]['TOT'];
    $totalTime = empty($totalTime) ? 1 : $totalTime;
    for ($i=0; $i<$stopSize; $i++) {
    $this->_stops[$i]['weight'] = round(60 * $this->_stops[$i]['DELTA'] / $totalTime);
    }
    }

    }

    $GLOBALS['Bs_StopWatch'] =& new Bs_StopWatch(); //pseudo static

    // -----------------------------------------------------------------------------------------
    // -----------------------------------------------------------------------------------------
    // -----------------------------------------------------------------------------------------
    // -----------------------------------------------------------------------------------------

    /*** TEST Stuff */

    if (basename($_SERVER['PHP_SELF']) == 'Bs_StopWatch.class.php') {
    ###################################################################################################
    $myStopWatch =& new Bs_StopWatch();
    $myStopWatch->reset();

    for ($i=0; $i<200000; $i++) {;} // Use some CPU
    $myStopWatch->takeTime("Take 1"); // Take time

    for ($i=0; $i<30000; $i++) {;} // Use some more CPU
    $myStopWatch->takeTime("Take 2"); // Take time again

    for ($i=0; $i<60000; $i++) {;}
    $myStopWatch->takeTime("Take 3");

    for ($i=0; $i<100000; $i++) {;}
    $myStopWatch->takeTime("Take 4"); // Last time take.

    // Output as HTML
    echo $myStopWatch->toHtml("This is the result of toHtml():");

    // Output as Text
    echo "<br><hr><pre>";
    echo $myStopWatch->toString("This is the result of toString():");
    echo "</pre><br>";

    echo 'and here is the code: <br><hr><br>';
    highlight_string(join('', file(__FILE__)));
    }


    ?>
    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More Date Time Code Articles
    More By Codewalkers

     

    IBM® developerWorks developerWorks - FREE Tools!


    IBM DB2 Deep Compression ROI Tool

    The IBM DB2 Deep Compression ROI tool is designed for DBA’s and IT management personnel to perform a clinical analysis of the cost savings gained from the Storage Optimization feature of DB2 9 for Linux, UNIX and Windows. The feature, also known as Deep Compression, compresses data that lies within a database by up to 80% at times.
    FREE! Go There Now!


    NEW! Accelerating Software Innovation on i on Power Systems

    Attend this launch webcast with Scott Hebner, Vice President of IBM Rational Marketing and Strategy, for an overview of Rational’s new software offerings and resources to help modernize and accelerate software innovation on i on Power Systems – while ensuring past application investments are protected and continue to grow. Learn how these solutions are helping customers extend their core i5/OS solutions toward modern architectures such as SOA and web technologies to deliver business improvements that stand the test of time.
    FREE! Go There Now!


    NEW! Applying lean thinking to the governance of software development

    Effective governance for lean development isn’t about command and control. Instead, the focus is on enabling the right behaviors and practices through collaborative and supportive techniques. Hear from Scott Ambler on how it is far more effective to motivate people to do the right thing than it is to force them to do so. Learn how to form a lightweight, collaboration-based framework that reflects the realities of modern IT organizations.
    FREE! Go There Now!


    NEW! Build Web services with transport-level security using Rational Application Developer V7, Part 1: Build Web services and Web services clients

    Build secure Web services with transport-level security using IBM Rational Application Developer V7 and IBM WebSphere Application Server V6.1. Follow this three-part series for step-by-step instructions about how to develop Web services and clients, configure HTTP basic authentication, and configure HTTP over SSL (HTTPS). This first part of the series walks you through building a Web service for a simple calculator application. You generate and test two different types of Web services clients: a Java Platform, Enterprise Edition (Java EE) client and a stand-alone Java client. You also handle user-defined exceptions in Web services.
    FREE! Go There Now!


    NEW! Hello World: WebSphere Service Registry and Repository

    Manage, govern, and share services across your organization by using WebSphere Service Registry and Repository. Follow the hands-on exercises to learn how to navigate the Web interface to publish, find, reuse, and update services.
    FREE! Go There Now!


    NEW! Rational 'Talks to You' Teleconference Series

    This Fall, IBM Rational talks to you directly through a special teleconference series giving you access to the best minds in IBM Rational - product experts and market thought leaders who will answer your questions during these pre-scheduled telephone conference calls. Register today!
    FREE! Go There Now!


    NEW! Section 508 of the U.S. Rehabilitation Act: Web accessibility compliance

    Because access to government information continues to be an area of concern for many U.S. citizens with disabilities, the U.S. government enacted Section 508 of the Rehabilitation Act in 2001 to ensure that government agencies create accessible Web content, enabling all citizens to access the information they need. A fully accessible Web site makes Web content accessible to all individuals, including those with disabilities, who may be accessing Web content via a variety of user agents. Common user agents include standard Web browsers, text-only browsers, assistive devices and mobile devices such as cell phones or personal digital assistants (PDAs).
    FREE! Go There Now!


    NEW! Trial download: IBM Rational Method Composer V7.2

    Get a free trial download of the latest version of IBM Rational Method Composer V7.2 which helps you deliver customized yet consistent process guidance to your project teams and IT organization, and includes the latest version of IBM Rational Unified Process (RUP), which has provided process guidance to teams since 1996.
    FREE! Go There Now!


    NEW! Try the IBM SOA Sandbox for Connectivity

    Visit IBM developerWorks to try the IBM SOA Sandbox for connectivity. The SOA Sandbox for connectivity provides a trial environment with the tooling and components to help you explore how to effectively connect your infrastructure and integrate all of the people, processes and information in your company. Use the hosted sandbox to explore SOA techniques that streamline connecting existing IT assets together, as well as learn how to connect them to new business logic.
    FREE! Go There Now!


    NEW! Webcast: Introducing the new Information Server and Solutions community: LeverageInformation

    User communities play an important role in communication and collaboration around products, solutions and other areas of special interest to members. Successful communities are able to provide the right mix of content and services to deliver a value proposition that resonates with each audience. Join Tom Inman, VP of Marketing for Information and Platform Solutions as he introduces the new LeverageINFORMATION community. During this webcast, learn about the value provided by the community and how customers and partners derive value from the community in addressing their own technical and business challenges.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    DATE TIME CODE ARTICLES

    - DaysInSpan.php
    - MySQLdateSpan.php
    - DateSpan.php
    - FutureDateFormEntry.php
    - Generate Time Option List for Select stateme...
    - Current Age Script (v2)
    - class for some mysql imitated time functions
    - Current Age Script, up to the last day
    - filemtime_remote
    - Page Generation Time Figure-Outer
    - convGMT v2
    - Benchmarker
    - Simple PHP Calendar
    - Display message according to hour of day
    - Display Date Function





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek