Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Timer Laravel Package

desarrolla2/timer

Lightweight PHP timer utility for measuring execution time. Start/stop laps, track multiple timers, and get elapsed time for profiling and benchmarking small code sections. Suitable for quick performance checks during development.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require desarrolla2/timer
    

    No service provider or facade registration is required—just autoload the Timer class:

    use Desarrolla2\Timer\Timer;
    
  2. First Use Case: Start a timer in a controller/middleware:

    $timer = new Timer('user_action');
    $timer->start();
    

    Later, stop and log the duration:

    $timer->stop();
    $duration = $timer->getDuration(); // Returns seconds as float
    
  3. Where to Look First:

    • Source Code (if available) for customization.
    • Timer class methods: start(), stop(), pause(), resume(), getDuration().
    • No config file—defaults are hardcoded (e.g., precision to milliseconds).

Implementation Patterns

Workflows

  1. Request Timing:

    // Middleware: Track request processing time
    public function handle($request, Closure $next) {
        $timer = new Timer('request_' . $request->ip());
        $response = $next($request);
        $timer->stop();
        Log::info("Request took {$timer->getDuration()}s");
        return $response;
    }
    
  2. Task Segmentation:

    $timer = new Timer('data_processing');
    $timer->start();
    
    // ... business logic ...
    
    $timer->pause(); // Pause before I/O operations
    sleep(2);        // Simulate delay
    $timer->resume();
    
    $timer->stop();
    
  3. Benchmarking:

    $timers = [];
    $timers['db_query'] = new Timer('db_query');
    $timers['db_query']->start();
    
    DB::query()->get(...);
    
    $timers['db_query']->stop();
    $total = $timers['db_query']->getDuration();
    

Integration Tips

  • Laravel Logging: Use Log::debug() with timer data for structured logs:

    Log::debug('Timer', [
        'name' => $timer->getName(),
        'duration' => $timer->getDuration(),
        'status' => $timer->isRunning() ? 'running' : 'stopped',
    ]);
    
  • Artisan Commands: Profile CLI tasks:

    $timer = new Timer('artisan_command');
    $timer->start();
    // ... command logic ...
    $timer->stop();
    echo "Executed in {$timer->getDuration()}s";
    
  • Queue Jobs: Track job execution time in handle():

    public function handle() {
        $timer = new Timer('job_' . $this->job->id);
        $timer->start();
        // ... job logic ...
        $timer->stop();
        $this->logDuration($timer);
    }
    

Gotchas and Tips

Pitfalls

  1. Precision:

    • Default precision is milliseconds (float). For microsecond precision, extend the class:
      $timer = new Timer('high_precision', microtime(true));
      
  2. Static State:

    • No built-in way to track multiple timers globally. Use an array or service container:
      $app->singleton('timers', function() {
          return collect();
      });
      
  3. Thread Safety:

    • Not thread-safe. Avoid using in queues/workers without synchronization.
  4. Memory Leaks:

    • Timers retain state in memory. Manually unset() or use dependency injection for short-lived timers.

Debugging

  • Check Running Timers:

    if ($timer->isRunning()) {
        echo "Timer paused at {$timer->getPausedAt()}s";
    }
    
  • Log All Timers:

    $timer->log(); // Outputs to storage/logs/laravel.log by default
    

Extension Points

  1. Custom Storage: Override storeDuration() to save to a database:

    $timer->storeDuration(function($duration) {
        DB::table('timer_logs')->insert([
            'name' => $timer->getName(),
            'duration' => $duration,
            'created_at' => now(),
        ]);
    });
    
  2. Event Triggers: Extend to dispatch events on start/stop:

    $timer = new Timer('event_timer');
    event(new TimerStarted($timer));
    $timer->start();
    
  3. Time Units: Add custom getters for readability:

    public function getDurationInMinutes() {
        return $this->getDuration() / 60;
    }
    

Config Quirks

  • No Config File: All defaults (e.g., log path) are hardcoded. Override via dependency injection:
    $timer = new Timer('custom', null, storage_path('logs/timers.log'));
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle