Obtener el tiempo transcurrido en Objective-C


Necesito obtener el tiempo transcurrido entre dos eventos, por ejemplo, la aparición de una UIView y la primera reacción del usuario.

¿Cómo puedo lograrlo en Objective-C?

Author: Pang, 2009-04-12

7 answers

NSDate *start = [NSDate date];
// do stuff...
NSTimeInterval timeInterval = [start timeIntervalSinceNow];

timeInterval es la diferencia entre inicio y ahora, en segundos, con una precisión de menos de milisegundos.

 260
Author: Can Berk Güder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-04-12 14:15:09

No debe confiar en [NSDate date] para fines de tiempo, ya que puede informar sobre o sobre el tiempo transcurrido. ¡Incluso hay casos en los que su computadora aparentemente viajará en el tiempo, ya que el tiempo transcurrido será negativo! (Por ejemplo, si el reloj se movió hacia atrás durante el tiempo.)

Según Aria Haghighi en la conferencia "Advanced iOS Gesture Recognition" del curso de invierno 2013 de Stanford iOS (34:00), usted debe utilizar CACurrentMediaTime() si necesita un tiempo preciso intervalo.

Objetivo-C:

#import <QuartzCore/QuartzCore.h>
CFTimeInterval startTime = CACurrentMediaTime();
// perform some action
CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;

Swift:

let startTime = CACurrentMediaTime()
// perform some action
let elapsedTime = CACurrentMediaTime() - startTime

La razón es que [NSDate date] se sincroniza en el servidor, por lo que podría conducir a "hipo de sincronización de tiempo" que puede conducir a errores muy difíciles de rastrear. CACurrentMediaTime(), por otro lado, es un tiempo de dispositivo que no cambia con estas sincronizaciones de red.

Necesitará agregar el marco QuartzCore a la configuración de su destino.

 206
Author: Senseful,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:51

Utilice el método timeIntervalSinceDate

NSTimeInterval secondsElapsed = [secondDate timeIntervalSinceDate:firstDate];

NSTimeInterval es solo un double, define en NSDate así:

typedef double NSTimeInterval;
 23
Author: Marco Lazzeri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-09 14:48:51

Para cualquiera que venga aquí buscando una implementación de GetTickCount () para iOS, aquí está la mía después de juntar varias fuentes:

#include <mach/mach.h>
#include <mach/mach_time.h>

uint64_t getTickCount(void)
{
    static mach_timebase_info_data_t sTimebaseInfo;
    uint64_t machTime = mach_absolute_time();

    // Convert to nanoseconds - if this is the first time we've run, get the timebase.
    if (sTimebaseInfo.denom == 0 )
    {
        (void) mach_timebase_info(&sTimebaseInfo);
    }

    // Convert the mach time to milliseconds
    uint64_t millis = ((machTime / 1000000) * sTimebaseInfo.numer) / sTimebaseInfo.denom;
    return millis;
}
 14
Author: Wayne Uroda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-21 12:04:54

Para las mediciones de tiempo de percepción (como GetTickCount), también eche un vistazo a mach_absolute_time y esta Apple Q & A: http://developer.apple.com/qa/qa2004/qa1398.html .

 9
Author: Jason Coco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-04-12 15:06:25

Use la función timeIntervalSince1970 de la clase NSDate como se muestra a continuación:

double start = [startDate timeIntervalSince1970];
double end = [endDate timeIntervalSince1970];
double difference = end - start;

Básicamente, esto es lo que uso para comparar la diferencia en segundos entre 2 fechas diferentes. también revise este enlace aquí

 5
Author: Raj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-04-12 14:16:25

Las otras respuestas son correctas (con una advertencia*). Añado esta respuesta simplemente para mostrar un ejemplo de uso:

- (void)getYourAffairsInOrder
{
    NSDate* methodStart = [NSDate date];  // Capture start time.

    // … Do some work …

    NSLog(@"DEBUG Method %s ran. Elapsed: %f seconds.", __func__, -([methodStart timeIntervalSinceNow]));  // Calculate and report elapsed time.
}

En la consola del depurador, se ve algo como esto:

DEBUG Method '-[XMAppDelegate getYourAffairsInOrder]' ran. Elapsed: 0.033827 seconds.

*Advertencia: Como otros mencionaron, use NSDate para calcular el tiempo transcurrido solo con fines casuales. Uno de esos propósitos podría ser pruebas comunes, perfiles crudos, donde solo quieres una idea aproximada de cuánto tiempo está tomando un método.

El riesgo es que la configuración de hora actual del reloj del dispositivo pueda cambie en cualquier momento debido a la sincronización del reloj de red. Así que NSDate el tiempo podría saltar hacia adelante o hacia atrás en cualquier momento.

 1
Author: Basil Bourque,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-31 00:41:55