root/src/modules-lua/noit/timeval.lua

Revision 88a71780101cbf23034aa0cb840f9f0368fda2dd, 2.4 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 5 years ago)

fixes #126

  • Property mode set to 100644
Line 
1 -- Copyright (c) 2008, OmniTI Computer Consulting, Inc.
2 -- All rights reserved.
3 --
4 -- Redistribution and use in source and binary forms, with or without
5 -- modification, are permitted provided that the following conditions are
6 -- met:
7 --
8 --     * Redistributions of source code must retain the above copyright
9 --       notice, this list of conditions and the following disclaimer.
10 --     * Redistributions in binary form must reproduce the above
11 --       copyright notice, this list of conditions and the following
12 --       disclaimer in the documentation and/or other materials provided
13 --       with the distribution.
14 --     * Neither the name OmniTI Computer Consulting, Inc. nor the names
15 --       of its contributors may be used to endorse or promote products
16 --       derived from this software without specific prior written
17 --       permission.
18 --
19 -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 -- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 local base = _G
32 local string = require("string")
33 module("noit.timeval")
34
35 local metat = { }
36
37 function new(sec, usec)
38   local o = base.setmetatable( { sec = sec, usec = usec }, metat)
39   return o
40 end
41
42 function now()
43   return new(base.noit.gettimeofday())
44 end
45
46 function metat.__add(o1, o2)
47   local secs = o1.sec + o2.sec
48   local usecs = o1.usec + o2.usec
49   if usecs > 1000000 then
50     usecs = usecs - 1000000
51     secs = secs + 1
52   end
53   return new(secs, usecs)
54 end
55
56 function metat.__sub(o1, o2)
57   local secs = o1.sec - o2.sec
58   local usecs = o1.usec - o2.usec
59   if usecs < 0 then
60     secs = secs - 1
61     usecs = 1000000 + usecs
62   end
63   if secs < 0 then
64     secs = secs + 1
65     usecs = usecs - 1000000
66   end
67   return new(secs, usecs)
68 end
69
70 function metat.__tostring(a)
71   return string.format("%f", (1.0 * a.sec) + (a.usec/1000000.0))
72 end
Note: See TracBrowser for help on using the browser.