1

I'm using gettimeofday in my program for time intervals like that:

struct timeval currentTime, startTime; 
gettimeofday(&startTime, NULL);
startTime.tv_usec /= 1000;
gettimeofday(&currentTime, NULL);
currentTime.tv_usec /= 1000;

long int msSinceStart = (currentTime.tv_usec + (1000 * currentTime.tv_sec) ) - (startTime.tv_usec + (1000 * startTime.tv_sec) );

Is there any alternative for this?

Gilad
  • 121
  • 1
  • 8
  • 1
    `gettimeofday` deprecated with Xcode 5.1 ?? where this came from ? – Emmanuel Mar 20 '14 at 13:07
  • it shows a warning "implicit declaration of function 'gettimeofday' is invalid in c99" – Gilad Mar 20 '14 at 15:57
  • 4
    Implicit declaration of a function, doesn't mean deprecated… Just include and the error vanished. – Emmanuel Mar 20 '14 at 16:01
  • @user2282782 your question should be demanding solution, if there is no option then should go for alternative, emmanuel is right – maddy Dec 15 '14 at 15:54

4 Answers4

3

@user2282782 Noted in their comments that the real issue behind the question was that the warning gettimeofday is invalid in c99 is being thrown in at compile time.

To resolve the issue, as @Emmanuel pointed out, just add:
#include <sys/time.h> to the top of the file. That solved my same problem with this as well.

kbpontius
  • 3,867
  • 1
  • 30
  • 34
2

You can also use CFAbsoluteTimeGetCurrent:

CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();

and to get the number of seconds that have elapsed:

CFTimeInterval elapsed = CFAbsoluteTimeGetCurrent() - start;

Note, the documentation for CFAbsoluteTimeGetCurrent warns us:

Repeated calls to this function do not guarantee monotonically increasing results. The system time may decrease due to synchronization with external time references or due to an explicit user change of the clock.

This means that if you're unfortunate enough to measure elapsed time when one of these adjustments take place, you can end up with incorrect elapsed time calculation. This caveat also applies to NSDate and similar functions. To get around this, you can use CACurrentMediaTime:

CFTimeInterval start = CACurrentMediaTime();

and

CFTimeInterval elapsed = CACurrentMediaTime() - start;

This uses mach_absolute_time, but avoids some of its complexities outlined in Technical Q&A QA1398.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
1

The Objective-C alternative is NSDate.

NSDate *startTime = [NSDate date];
NSTimeInterval secondsSinceStart = -[startTime timeIntervalSinceNow];

Of course, if you want a hi-res time, you should be using mach_absolute_time (see https://developer.apple.com/library/mac/qa/qa1398/_index.html).

Jody Hagins
  • 27,943
  • 6
  • 58
  • 87
1

Now to resolve this issue you should insert to your file this:

#import <UIKit/UIKit.h>

EddieG
  • 49
  • 1
  • 5