Obtener tiempo en milisegundos usando C#


Estoy haciendo un programa en el que necesito obtener el tiempo en milisegundos. Por tiempo, me refiero a un número que nunca es igual a sí mismo, y siempre es 1000 números más grandes de lo que era hace un segundo. He intentado convertir DateTime.Now a un TimeSpan y obtener el TotalMilliseconds de eso... pero he oído que no es perfectamente exacto.

Hay una manera más fácil de hacer esto?

Author: Peter Mortensen, 2010-10-25

7 answers

Utilice el Stopwatch clase.

Proporciona un conjunto de métodos y propiedades que puede utilizar para medir con precisión el tiempo transcurrido.

Hay una buena información sobre su implementación aquí:

Pruebas de Rendimiento: Mediciones Precisas del Tiempo de Ejecución con el Sistema.Diagnostico.Cronómetro

 67
Author: RedFilter,
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
2010-10-25 16:05:37
long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;

Así es como se implementan los diversos métodos de conversión de Unix en el DateTimeOffset clase (. NET Framework 4.6+,. NET Standard 1.3+):

long milliseconds = DateTimeOffset.Now.ToUnixTimeMilliseconds();
 239
Author: Evan Mulawski,
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-11 18:00:03

La propiedad DateTime.Ticks obtiene el número de marcas que representan la fecha y la hora.

10,000 garrapatas es un milisegundo (10,000,000 garrapatas por segundo).

 11
Author: Itay Karo,
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
2015-07-16 08:25:48

Puede probar el método nativo QueryPerformanceCounter. Véase http://www.pinvoke.net/default.aspx/kernel32/QueryPerformanceCounter.html para más información. Esto es lo que usa la clase Stopwatch.

Ver ¿Cómo obtener la marca de tiempo de precisión de tick en. NET / C#? para más información.

Stopwatch.GetTimestamp() da acceso a este método:

public static long GetTimestamp() {
     if(IsHighResolution) {
         long timestamp = 0;
         SafeNativeMethods.QueryPerformanceCounter(out timestamp);
         return timestamp;
     }
     else {
         return DateTime.UtcNow.Ticks;
     }
 }
 6
Author: Pieter van Ginkel,
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:47:16

Utilizo la siguiente clase. Lo encontré en Internet una vez, postulado para ser el mejor AHORA().

/// <summary>Class to get current timestamp with enough precision</summary>
static class CurrentMillis
{
    private static readonly DateTime Jan1St1970 = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    /// <summary>Get extra long current timestamp</summary>
    public static long Millis { get { return (long)((DateTime.UtcNow - Jan1St1970).TotalMilliseconds); } }
}

Fuente desconocida.

 5
Author: schmijos,
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
2013-02-24 12:59:00

Usé DateTime.Ahora.Hora del día.Totalmillisegundos (para el día actual), espero que te ayude también.

 4
Author: Sarvan,
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-08-17 09:57:00

Use System.DateTime.Now.ToUniversalTime(). Eso pone su lectura en un formato conocido de milisegundos basado en referencias que elimina totalmente el cambio de día, etc.

 1
Author: John Tobler,
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
2016-12-15 19:10:08