Skip to content

Instantly share code, notes, and snippets.

@mfurquimdev
Created August 16, 2014 20:53
Show Gist options
  • Save mfurquimdev/c7c3e382892801fd2634 to your computer and use it in GitHub Desktop.
Save mfurquimdev/c7c3e382892801fd2634 to your computer and use it in GitHub Desktop.
Operators for struct timeval
#include <iostream>
#include <stdlib.h>
#include <sys/time.h>
#include "timeval_operators.h"
using namespace std;
int main(int argc, char* argv[])
{
timeval t0, t1;
gettimeofday(&t0, NULL);
for (int i = 0; i < 1000000; i++);
gettimeofday(&t1, NULL);
cout << (t1 - t0) << endl;
return 0;
}
#ifndef TIMEVALOPERATORS_H
#define TIMEVALOPERATORS_H
using namespace std;
// ********** struct timeval: overloaded operators **********
// ***** output *****
inline ostream& operator<<(ostream& out,struct timeval tv)
{
out << "sec: " << tv.tv_sec << " usec: " << tv.tv_usec;
return out;
}
// ***** comparison *****
inline bool operator<(struct timeval t0,struct timeval t1)
{
return
t0.tv_sec < t1.tv_sec ||
t0.tv_sec == t1.tv_sec && t0.tv_usec < t1.tv_usec;
}
inline bool operator<=(struct timeval t0,struct timeval t1)
{
return
t0.tv_sec < t1.tv_sec ||
t0.tv_sec == t1.tv_sec && t0.tv_usec <= t1.tv_usec;
}
inline bool operator==(struct timeval t0,struct timeval t1)
{
return t0.tv_sec == t1.tv_sec && t0.tv_usec == t1.tv_usec;
}
inline bool operator!=(struct timeval t0,struct timeval t1)
{
return !(t0 == t1);
}
inline bool operator>(struct timeval t0,struct timeval t1)
{
return !(t0 <= t1);
}
inline bool operator>=(struct timeval t0,struct timeval t1)
{
return !(t0 < t1);
}
// ***** arithmetic *****
// pre: t0 + t1 representable in a struct timeval
inline struct timeval operator+(struct timeval t0,struct timeval t1)
{
struct timeval t = {t0.tv_sec+t1.tv_sec,t0.tv_usec+t1.tv_usec};
if (t.tv_usec >= 1000000) { // carry needed
t.tv_sec++;
t.tv_usec -= 1000000;
}
return t;
}
// pre: t0 + t1 representable in a struct timeval
inline struct timeval operator+=(struct timeval& t0,struct timeval t1)
{
t0.tv_sec += t1.tv_sec;
t0.tv_usec += t1.tv_usec;
if (t0.tv_usec >= 1000000) { // carry needed
t0.tv_sec++;
t0.tv_usec -= 1000000;
}
return t0;
}
// pre: t0 >= t1
inline struct timeval operator-(struct timeval t0,struct timeval t1)
{
struct timeval t = {t0.tv_sec-t1.tv_sec,t0.tv_usec-t1.tv_usec};
if (t.tv_usec < 0) { // borrow needed
t.tv_sec--;
t.tv_usec += 1000000;
}
return t;
}
// pre: t0 >= t1
inline struct timeval operator-=(struct timeval& t0,struct timeval t1)
{
t0.tv_sec -= t1.tv_sec;
t0.tv_usec -= t1.tv_usec;
if (t0.tv_usec < 0) { // borrow needed
t0.tv_sec--;
t0.tv_usec += 1000000;
}
return t0;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment