SunQuest
 
       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  
Forums Sitemap 
Dedicated Servers  
Download TestComplete 
IBM® developerWorks
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
IBM developerWorks
 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

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    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 – Taking Web 2.0 to Work

    You'll get answers to many questions and more from David Barnes, Lead Evangelist for IBM Emerging Internet Technologies. David will discuss aspects of Web 2.0 that bring value to corporations, academia, and government. He'll also discuss IBM's vision around Web 2.0, including the importance of remixability and consumability. The discussion will culminate with examples of various IBM Software Group solutions you can use to get ahead of the Web 2.0 adoption curve.
    FREE! Go There Now!


    NEW! A Layered approach to delivering security-rich Web applications

    As businesses grow increasingly dependent upon Web applications to provide services to customers, employees and partners, these complex applications become more difficult to secure. Although traditional security solutions protect Internet infrastructure layers, they do not guard against HTTP and HTML attacks. Many organizations that conduct security testing still deploy applications that allow attackers to manipulate their logic and wreak havoc on their business. To mitigate this risk, development and delivery teams must address Web application security throughout the lifecycle, addressing the many layers detailed in this paper.
    FREE! Go There Now!


    NEW! Achieving True Agility -- How process can change the behavior of your tools

    Achieving true agility is a never-ending effort. We will showcase how you can become agile incrementally, a few practices at the time.Which practices should any agile team strive to adopt? What additional practices should you consider based on your needs to scale? Adopting practices are however made much easier with the right tool support. What about if your tools adapt to your practices? We will take a look at how the Jazz technology can be leveraged to make your process change the behavior of your tools.
    FREE! Go There Now!


    NEW! Develop Systems Software Assets with IBM Rational Asset Manager

    Join us for this on demand webcast to learn about developing complex systems more quickly and efficiently. We'll cover market drivers for developing, governing and reusing systems software assets and how you can develop system software assets with Rational Asset Manager.
    FREE! Go There Now!


    NEW! Download IBM Data Studio V1.1

    Visit IBM developerWorks to download the latest trial version of IBM Data Studio V1.1 at no cost. IBM Data Studio is a comprehensive data management solution that helps you effectively design, develop, deploy and manage your data, databases, and database applications throughout the data management life cycle utilizing a consistent and integrated user interface. Unlike other client-side data management solutions that focus on only one aspect of the application lifecycle or database administration, Data Studio complements the Rational Software Delivery platform, providing unparalleled flexibility for a heterogeneous data server environment across platforms.
    FREE! Go There Now!


    NEW! Evaluate IBM Rational Developer for System i V7.1

    Download a free trial version of IBM Rational Developer for System i V7.1, which provides a complete development environment for traditional i5/OS application development. IBM Rational Developer for System i is a new eclipse-based workstation offering for i5/OS application development that provides a comprehensive Integrated Development Environment for edit/compile/debug of traditional RPG/COBOL/C/C++ i5/OS applications.
    FREE! Go There Now!


    NEW! Improve your build process with IBM Rational Build Forge, Part 2: Automate builds for a real-world Tomcat project

    Learn how Rational Build Forge can extend a simple compile and package build process by adding customization and deployment capability. Go from a manual method to automating: checking for code changes; getting the latest source; compiling and packaging; customizing; copying to and restarting a deployment server; and sending e-mail notification that a new version is available.
    FREE! Go There Now!


    NEW! Using IBM Rational Developer for System z and IBM Rational ClearCase together to manage application development

    Whether you are creating new applications or modifying existing ones, managing integration of new components with traditional z/OS elements is a critical part of building and deploying modern applications. Listen to this webcast to see how IBM can help you optimize your development process using an IDE like Rational Developer for System z that integrates with management tools, such as ClearCase to manage your application development on mainframes.
    FREE! Go There Now!


    NEW! Webcast: WebSphere Process Server

    WebSphere Process Server delivers a unique integration framework that simplifies existing IT resources. Often, as IT assets grow to support business demand, so too does their complexity and manageability. In this webcast, we’ll discuss how WebSphere Process Server helps deliver an SOA infrastructure that provides a common model to orchestrate, mediate, connect, map, and execute the underlying IT functions. Discover how WebSphere Process Server simplifies integration of business processes by leveraging existing IT assets as reusable services without the complexities of traditional integration methodologies.
    FREE! Go There Now!


    NEW! Webcast: What is new in Viper 2 for developers?

    Viper 2 brings a great value to developer communities including SQL, XML, PHP, Ruby, .NET and Java. You probably already know that DB2 Express-C is free for developers to develop, deploy and distribute. Viper 2 provides a variety of means that help move your application from the development stage to deployment more rapidly. This webcast shows how to best utilize the latest tools available for developing DB2 applications.
    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-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway