File: timing.pyx

package info (click to toggle)
pyepl 1.1.0-3.1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 2,120 kB
  • sloc: cpp: 7,986; python: 6,026; makefile: 360; ansic: 132
file content (75 lines) | stat: -rw-r--r-- 1,993 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# PyEPL: hardware/timing.pyx
#
# Copyright (C) 2003-2005 Michael J. Kahana
# Authors: Ian Schleifer, Per Sederberg, Aaron Geller, Josh Jacobs
# URL: http://memory.psych.upenn.edu/programming/pyepl
#
# Distributed under the terms of the GNU Lesser General Public License
# (LGPL). See the license.txt that came with this file.

"""
This module provides low-level timing functionality.
"""

import pygame
from pygame.time import get_ticks, delay, wait
import time
from eventpoll import pollEvents

cdef object basetime
basetime = long(0)

cdef extern from "unistd.h":
    int usleep (long)

def initialize(**options):
    """
    Do any preparation necessary before using timing features.
    """
    global basetime
    basetime = long(round(time.time() * 1000)) - get_ticks()

def finalize():
    """
    Shut down timing features.
    """
    pass

def universal_time():
    """
    Returns the number of milliseconds elapsed since the unix epoch.
    """
    global basetime
    return basetime + get_ticks()

def timedCall(t, f, *targs, **dargs):
    """
    At time t, call f with any remaining arguments.  Returns a 2-tuple
    of a timestamp for the time and maximum latency of the actual call
    to f, and the return value of the call.  If t is None or 0, the
    call is made immediately.

    INPUT ARGS:
      t- time at which to execute call.  This can be specified as an
         integer specifying a millisecond time to run,
         OR as a PresentationClock object.
      f- a callable to run at the specified time
      args- arguments to pass to f when it is called.
    
    """
    if t:
        # if t is a PresentationClock, then (we think) the t.get()
        # method is called during the comparison
        while t > universal_time():
            pollEvents()
    before = universal_time()
    r = f(*targs, **dargs)
    after = universal_time()

    return ((before, after - before + 1), r)

def uSleep(usec):
    """
    Force a usec sleep.
    """
    usleep(usec)