source: libcaca/trunk/caca/time.c @ 2305

Last change on this file since 2305 was 2305, checked in by Sam Hocevar, 12 years ago
  • Remove all unsigned ints from exported functions. Signed arithmetic is far better for error checking.
  • Property svn:keywords set to Id
File size: 2.2 KB
Line 
1/*
2 *  libcaca       Colour ASCII-Art library
3 *  Copyright (c) 2002-2006 Sam Hocevar <sam@zoy.org>
4 *                All Rights Reserved
5 *
6 *  $Id: time.c 2305 2008-04-19 19:25:52Z sam $
7 *
8 *  This library is free software. It comes without any warranty, to
9 *  the extent permitted by applicable law. You can redistribute it
10 *  and/or modify it under the terms of the Do What The Fuck You Want
11 *  To Public License, Version 2, as published by Sam Hocevar. See
12 *  http://sam.zoy.org/wtfpl/COPYING for more details.
13 */
14
15/*
16 *  This file contains simple timer routines.
17 */
18
19#include "config.h"
20
21#if !defined(__KERNEL__)
22#   include <stdlib.h>
23#   if defined(HAVE_SYS_TIME_H)
24#       include <sys/time.h>
25#   endif
26#   include <time.h>
27#   if defined(USE_WIN32)
28#       include <windows.h>
29#   endif
30#   if defined(HAVE_UNISTD_H)
31#       include <unistd.h>
32#   endif
33#endif
34
35#include "caca.h"
36#include "caca_internals.h"
37
38void _caca_sleep(int usec)
39{
40#if defined(HAVE_USLEEP)
41        usleep(usec);
42#elif defined(HAVE_SLEEP)
43        Sleep(usec / 1000);
44#else
45        /* SLEEP */
46#endif
47}
48
49int _caca_getticks(caca_timer_t *timer)
50{
51#if defined(HAVE_GETTIMEOFDAY)
52    struct timeval tv;
53#elif defined(USE_WIN32)
54    static __int64 freq = -1; /* FIXME: can this move to caca_context? */
55    __int64 usec;
56#endif
57    int ticks = 0;
58    int new_sec, new_usec;
59
60#if defined(HAVE_GETTIMEOFDAY)
61    gettimeofday(&tv, NULL);
62    new_sec = tv.tv_sec;
63    new_usec = tv.tv_usec;
64#elif defined(USE_WIN32)
65    if(freq == -1)
66    {
67        if(!QueryPerformanceFrequency((LARGE_INTEGER *)&freq))
68            freq = 0;
69    }
70
71    QueryPerformanceCounter((LARGE_INTEGER *)&usec);
72    new_sec = (int)(usec * 1000000 / freq / 1000000);
73    new_usec = (int)((usec * 1000000 / freq) % 1000000);
74#endif
75
76    if(timer->last_sec != 0)
77    {
78        /* If the delay was greater than 60 seconds, return 10 seconds
79         * otherwise we may overflow our ticks counter. */
80        if(new_sec >= timer->last_sec + 60)
81            ticks = 60 * 1000000;
82        else
83        {
84            ticks = (new_sec - timer->last_sec) * 1000000;
85            ticks += new_usec;
86            ticks -= timer->last_usec;
87        }
88    }
89
90    timer->last_sec = new_sec;
91    timer->last_usec = new_usec;
92
93    return ticks;
94}
95
Note: See TracBrowser for help on using the repository browser.