My favorites | Sign in
Project Home Wiki Issues Source
READ-ONLY: This project has been archived. For more information see this post.
Project Information
Members

The timer manager achieved O(1) time complexity, which means it can manage millions of timers with out performance decrease.

Features

  • The algorithm is similar to 'time wheel', which guarantees the O(1) time complexity.
  • Granularity of expire time is customizable by custom get_time function, by default it is 1 ms.
  • Max number of time slice is 232-1, it is about 49 days with 1 ms granularity. Max number of timers in a manager instance is 232-1.
  • Timer objects are maintained by inner pools and free lists to avoid memory fragmentation, and are accessed by 'unsigned int' type timer_id.
  • Simple API and small timer object, only 29 bytes on 64-bit machine.

Performance

On Core 2 Duo E4500@2.2GHz/8GB RAM/7200RPM SATA/Linux 3.2.0-25(64-bit):

 Set 1,000,000 timers which will be expired in 10 seconds costs about 160ms;
 Poll these timer events every 10ms, 1000 polls in total. And close the timer when it triggered.
 All these operations consumes 0.51s cpu time(cpu user).
 These timers consumes 28MB memory in total.
 

Usage

A simple demo:

#include "libtimers.h"
#include <stdio.h>
#include <unistd.h>



int main()
{
    /* get a new timer pool object */
    LT_TIMERPOOL *pool = lt_new(NULL);
    for(int i = 1; i <= 10; i++) {
        /* get a new timer descriptor  */
        uint32_t tid = lt_timer_open(pool);

        /* assign a random data to the timer */
        int data = (10 - i) * 100;

        /* set the timer, it will time up at n-th seconds later */
        lt_set_timer(pool, tid, (void*)data, i * 1000);
    }


    while(lt_timer_size(pool) > 0) {
        /* sleep a while, or do something like select() between timer polls */
        usleep(10000);

        LT_TIMER_EVENT *events;
        /* poll timer events */
        int event_count = lt_poll(pool, &events);

        if (event_count > 0)
            printf("timer poll get %d events\n", event_count);

        for(int i = 0; i < event_count; ++i) {
            /* show something at time up */
            printf("Times up, data: %d\n", (int)events[i].data);

            /* force close(free) next timer before it times up */
            lt_timer_close(pool, events[i].timer_id + 1);
        }

        /* free events array after a poll */
        lt_free_events(pool, events);
    }

    /* free the pool */
    lt_destroy(pool);

    return 0;
}

 $ gcc test.c -std=gnu99 -static -ltimers -L./
 $ time ./a.out 
 timer poll get 1 events
 Times up, data: 900
 timer poll get 1 events
 Times up, data: 700
 timer poll get 1 events
 Times up, data: 500
 timer poll get 1 events
 Times up, data: 300
 timer poll get 1 events
 Times up, data: 100
 

 real    0m9.005s
 user    0m0.004s
 sys     0m0.000s
 

Powered by Google Project Hosting