iOS Game Center submit time elapsed - iphone

I'm trying to submit a double with the time that the user took to beat a stage. The leaderboard score format type is "Elapsed time - To the hundredth of a second". Something like this:
0:11:44.09
So I have a double that says the time is 11.734929 (it's 0:11:73). I multiply it to 6000 to convert it to int64_t. The result is 70409.572494. I can only send and int64_t so I'm losing 0.572494 seconds. The time sent is finally 0:11:44.09.
How can I send the full time instead of part of it?
EDIT:
I found the solution:
double my_time = ...
double intPart = 0;
double fractPart = modf(my_time, &intPart);
int isecs = (int)intPart;
int min = isecs / 60;
int sec = isecs % 60;
int hund = (int) (fractPart * 100);
int64_t time_to_send_through_game_center = min*6000 + (sec*100 + hund);

Not sure if this is what you are asking.
If you want 70409572.494 to be able to send 70409572, then multiply by 6000000 instead of 6000. This will convert 11.734929 to 70409572.494

Related

flutter - return/show plus sign of int

I'm trying to build some training app for functions for school. The problem is:
Everytime the randomly picked number is lower than 0, my function shows +-, because
I have a fixed format for my function.
EXAMPLE
I tried to use the NumberFormat of the Intl-Package, but then I can't use the int-values correctly. Is there a way to show a plus sign for positive numbers, while they are still usable to work with them?
Code so far:
int randomNumberMinMax(int min, int max){
int randomminmax = min + Random().nextInt(max - min);
if(randomminmax==0){
randomminmax = min + Random().nextInt(max - min);
}
//generate random number within minimum and maximum value
return randomminmax;
}
int a = randomNumberMinMax(-5, 5);
int b = randomNumberMinMax(-10, 10);
int c = randomNumberMinMax(-10, 10);
String task = "f(x) = $a(x+$b)²+ $c";
You could only show the plus when the number is positive like this for example
String task = "f(x) = $a(x${b >= 0 ? "+" : ""}$b)²${c >= 0 ? "+" : ""} $c";

How to convert the time to minutes of Timer

I have this time that starts when a product is initialized and I want to format it to 00:00 instead of just 0.
Timer _timer;
_startTimer(prod) {
prod.tempo = 0;
_timer = Timer.periodic(Duration(seconds: 1), (timer) {
setState(() {
prod.tempo++;
});
});
}`
[you can se the time in red I want to convert][1]
[1]: https://i.stack.imgur.com/vCv7p.jpg
If you have a total number of seconds, you can pretty print it with:
String toTimeField(int n) => n.toString().padLeft(2, '0');
var seconds = totalSeconds % 60;
var minutes = totalSeconds ~/ 60;
var prettyDuration = '${toTimeField(minutes)}:${toTimeField(seconds)}`;
That said, if you want to measure a duration, you're usually better off keeping track of the starting time and then computing the difference with the current time. That prevents accumulating error if there are any timing discrepancies from when your callback fires. You can use DateTime.now() to get the current time, store it, and then when your callback fires, call DateTime.now() again and subtract the original value. Or use the Stopwatch class, which does that for you. Using Stopwatch and Duration, you'd do:
_startTimer(prod) {
prod.stopwatch = Stopwatch();
...
}
...
final elapsed = prod.stopwatch.elapsed;
var seconds = elapsed.inSeconds % 60;
var minutes = elapsed.inMinutes;
Finally, I also recommend avoiding using : when printing durations since it could easily be misinterpreted. Does 12:34 represent a time? Does it represent 12 hours and 34 minutes or 12 minutes and 34 seconds? Printing durations as 12m34s is much clearer.
You can format the String as follows:
var seconds = prod.tempo % 60;
var minutes = (prod.tempo - seconds) / 60;
//if you have less than 10 seconds/minutes, prepend a '0':
String secondsAsString = seconds < 10 ? '0$seconds' : seconds;
String minutesAsString = minutes < 10 ? '0$minutes' : minutes;
String displayTime = 'Tempo: ' + secondsAsString + ':' + minutesAsString;

Displaying an integer from a string using the minute , second and isecond time format

Please can anyone help me out here, I wish to display the following:
for (int i = 0; i < [highScores count]; i++)
{
[scoresString appendFormat:#"%i. %i\n", i + 1, [[highScores objectAtIndex:i] intValue]];
}
As a time value in this format 00:00:00 (in minutes seconds and hundredths of a second). At the moment I am getting values such as 7008(note that i have my maximum time in seconds is defined as *# define MAX_TIME 7200*).
Please how do about doing this conversion.
As X Slash states, if your integer is in seconds then you can't get hundredths of a second, but to convert it to minutes and seconds, do this:
int total = [[highScores objectAtIndex:i] intValue];
int minutes = total / 60;
int seconds = total % 60;
[scoresString appendFormat:#"%i. %02i:%02i\n", i + 1, minutes, seconds];
Note the 02 between the % and i - that means space out the number to two characters and insert leading zeros.
Incidentally, if your seconds are coming out as 7008 then with the logic above you'll get a time of 116:48 - i.e. 116 minutes, 48 seconds. Are you sure your time is in seconds? If it is you may wish to add an hours column.

Format a float value to get the digits before a decimal point

In my application I have a music player, which plays music with a length of 0:30 seconds.
However in a UILabel I am currently displaying the progress, and as it is a float, the label is displaying i.e 14.765.
I would appreciate it if you could tell me how I could get the label to display
0:14 rather than 14.765.
Also, I would appreciate it if you could tell me how I could display 0:04 if the progress was 4seconds in.
This works properly:
float time = 14.765;
int mins = time/60;
int secs = time-(mins*60);
NSString * display = [NSString stringWithFormat:#"%d:%02d",mins,secs];
Results:
14.765 => 0:14
30.000 => 0:30
59.765 => 0:59
105.999 => 1:45
EDIT
In addition the 'one liner':
float time = 14.765;
NSString * display = [NSString stringWithFormat:#"%d:%02d",(int)time/60,(int)time%60];
You first need to convert your float to an integer, rounding as you wish. You can then use the integer division, /, and remainder, % operations to extract minutes and seconds and produce a string:
float elapsedTime = 14.765;
int wholeSeconds = round(elapsedTime); // or ceil (round up) or floor (round down/truncate)
NSString *time = [NSString stringWithFormat:#"%02d:%02d", wholeSeconds/60, wholeSeconds%60];
The %02d is the format specification for a 2-digits, zero padded, integer - look up printf in the docs for full details.
//%60 remove the minutes and int removes the floatingpoints
int seconds = (int)(14.765)%60;
// calc minutes
int minutes = (int)(14.765/60);
// validate if seconds have 2 digits
NSString time = [NSString stringWithFormat:#"%i:%02i",minutes,seconds];
that should work. Can't test it i'm on Win currently

How do I accurately time how long it takes to call a function on the iPhone?

I would like to know how long it's taking to send a message to an object with at least a 1ms accuracy. How do I do this?
You can use mach_absolute_time to measure in nanoseconds.
#import <mach/mach_time.h>
uint64_t startTime = 0;
uint64_t endTime = 0;
uint64_t elapsedTime = 0;
uint64_t elapsedTimeNano = 0;
mach_timebase_info_data_t timeBaseInfo;
mach_timebase_info(&timeBaseInfo);
startTime = mach_absolute_time();
//do something here
endTime = mach_absolute_time();
elapsedTime = endTime - startTime;
elapsedTimeNano = elapsedTime * timeBaseInfo.numer / timeBaseInfo.denom;
Reference:
Technical Q&A QA1398: Mach Absolute Time Units
Here's what I do:
NSDate * start = [NSDate date];
// do whatever I need to time
NSLog(#"time took: %f", -[start timeIntervalSinceNow]);
The output will be in seconds (with a decimal portion). NSDates have resolution on the scale of milliseconds, although I'm not sure precisely how accurate they are.
If the code you're trying to time is too fast, put it in a loop that runs the code a hundred times. (That assumes, of course, that the code you're timing has no side effects.)
Use dispatch_benchmark to log method execution time in nanoseconds.
It has a much nicer syntax than manually looping and calling mach_absolute_time() dispatch_benchmark is part of Grand Central Dispatch. This function is not publicly declared, so you’ll have to do that yourself before use :
extern uint64_t dispatch_benchmark(size_t count, void (^block)(void));
I am using this for log execution time :
size_t const blockIterations = 1; //block call count
uint64_t t = dispatch_benchmark(blockIterations, ^{ //your code inside block
[self TEST_processJSONDataRecordsWithCompletionHandler:^(id handler) {}];
});
NSLog(#" Avg. Runtime in nanoseconds : %llu ns", t);
Credit goes to Benchmarking