Midiendo tiempo de ejecución en C con time.h
Clase 10 de 12 • Curso de Funciones en C
Contenido del curso
Clase 10 de 12 • Curso de Funciones en C
Contenido del curso
Leandro Tenjo
Nicolas Esteban Prieto Sarmiento
Erick José González Cabrera
Federico Moreno
Danilo Toro
Irving Juárez
Jesús Ignacio García Fernández
Ivan Yerry Hinojosa Zegarra
Jesús Ignacio García Fernández
JUAN FRANCISCO ochoa lomas
Juan Pablo Perez
Reinaldo Mendoza
Dennys Medardo Heras Quintuña
David Lara
Samuel David Andrade Rivera
Jorge Hernández
Reinaldo Mendoza
Juan Francisco
Gabriel Obregón
DAMIÁN NICOLAS PINEDO
Leonardo Véliz
Marcelo Gaston Duarte
Jhon Sebastian Zuluaga Castañeda
Erik Ucenik
Pablo Cervantes Bohórquez
Ariel Ezequiel Biazzo Genua
Eber Laurente Lliuyacc
Jorge Varas
Pedro Muñoz Becerra
Daniel Esteban Solórzano Pinto
Si calculan el EPOCH time actual y le restan el de la clase, podrían saber que día se grabo el curso. 🤯
🤯 :0
Efectivamente el video lo grabaron el viernes 12 de junio de 2020
Jaja. Dale al 💚 si también pensaste que te daba un número distinto y estuviste 5 minutos revisando el código hasta que te diste cuenta que evidentemente tu resultado iba a tener más horas porque lo hiciste en el futuro. ¿Quién dijo Dark? 🕰
No me paso pero <3 igual
A nadie le paso pero ten tu corazon
Este e mi código, para que tarde algo más le hago escribir por consola y borrarla, ojo el borrado no es igual en Linux que en Windows, por lo que tendrán que comentar y descomentar según sea su máquina si quieren probar mi código.
#include <time.h> #include <stdlib.h> int main(void) { long i; long begin; long end; int hours; int minutes; int seconds; long aux; i = 0; begin = time(NULL); while (i < 600) { system("clear"); // Linux //system("cls"); // Windows printf("contandor %06d\n", i); i++; } end = time(NULL); aux = difftime(end, begin); hours = aux / 3600; minutes = aux / 60; seconds = aux % 60; printf("el tiempo transcurrido total es %d seg y equivale a %02d:%02d:%02d", aux, hours, minutes, seconds); return 0; }
Salida
contandor 000599 el tiempo transcurrido total es 19 seg y equivale a 00:00:19
Hice este contador de segundos. WARNING!!!!! Come mucha CPU
Según la ayuda de Linux o del WSL de Windows mas las librerías de C
man 2 time
TIME(2) Linux Programmer's Manual TIME(2) NAME time - get time in seconds SYNOPSIS #include <time.h> time_t time(time_t *tloc); DESCRIPTION time() returns the time as the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). If tloc is non-NULL, the return value is also stored in the memory pointed to by tloc. RETURN VALUE On success, the value of time in seconds since the Epoch is returned. On error, ((time_t) -1) is returned, and errno is set appropriately. ERRORS EFAULT tloc points outside your accessible address space (but see BUGS). On systems where the C library time() wrapper function invokes an implementation provided by the vdso(7) (so that there is no trap into the kernel), an invalid address may instead trigger a SIGSEGV signal. CONFORMING TO SVr4, 4.3BSD, C89, C99, POSIX.1-2001. POSIX does not specify any error conditions. NOTES POSIX.1 defines seconds since the Epoch using a formula that approximates the number of seconds between a specified time and the Epoch. This formula takes account of the facts that all years that are evenly divisible by 4 are leap years, but years that are evenly divisible by 100 are not leap years unless they are also evenly divisible by 400, in which case they are leap years. This value is not the same as the actual number of seconds between the time and the Epoch, because of leap seconds and because system clocks are not required to be synchronized to a standard reference. The intention is that the interpretation of seconds since the Epoch values be consistent; see POSIX.1-2008 Rationale A.4.15 for further rationale. On Linux, a call to time() with tloc specified as NULL cannot fail with the error EOVERFLOW, even on ABIs where time_t is a signed 32-bit integer and the clock ticks past the time 2**31 (2038-01-19 03:14:08 UTC, ignoring leap seconds). (POSIX.1 permits, but does not require, the EOVERFLOW error in the case where the seconds since the Epoch will not fit in time_t.) Instead, the behavior on Linux is undefined when the system time is out of the time_t range. Applications intended to run after 2038 should use ABIs with time_t wider than 32 bits. BUGS Error returns from this system call are indistinguishable from successful reports that the time is a few seconds before the Epoch, so the C library wrapper function never sets errno as a result of this call. The tloc argument is obsolescent and should always be NULL in new code. When tloc is NULL, the call cannot fail. C library/kernel differences On some architectures, an implementation of time() is provided in the vdso(7). SEE ALSO date(1), gettimeofday(2), ctime(3), ftime(3), time(7), vdso(7) COLOPHON This page is part of release 4.15 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at https://www.kernel.org/doc/man-pages/. Linux 2017-09-15 TIME(2)
comparto el codigo, utilizando algunas funciones que contine la libreria time.h
#include <stdio.h> #include <time.h> int main () { time_t t; t = time(NULL); printf(asctime(localtime(&t))); }
Me pase con los ceros y se me tildo el programa jaja.
Tranquilo, no sera la ultima vez que pase
jajajaja, yo estaba esperando pero no terminaba asi que lo cerre.
Como matar tu CPU en 10 líneas.... jejeje
Con este codigo pueden ver cuantos dias, horas, minutos y segundos han pasado desde EPOCH como en la pagina de la clase. ¡Feliz día!
#include <time.h> #include <stdlib.h> time_t hoy; int days,hrs,min,sec; int main(void) { hoy = time(NULL); printf("EPOCH es igual a %ld segundos \n", hoy); days = hoy/86400; hrs = (hoy % 86400) / 3600; min = ((hoy % 86400) % 3600) / 60; sec = ((hoy % 86400) % 3600) % 60; printf("Desde EPOCH han pasado %d dias, %d horas, %d minutos, %d segundos\n", days, hrs,min,sec); }
¿por qué null en la función null?
Porque recibe un paramaetro nulo, es decir, la funcion sabe que es lo que tiene que hacer y no necesita inputs para hacerlo
DATO_TERMINAL_ctrl+c
Si exageraste con los numeros de iteracion y la terminal no reacciona porque se demora mucho o el tipo de formato es muy corto para los numeros que ejecuta, puedes digitar CONTROL+C en la terminal para salir o interrumpir la ejecucion.
FORMATO %lf
Puede ser que por el tipo de formato c no pueda calcular la firencia de segundo puesto che f es muy corto para tantos numeros, en respuesta a esto puedes usar en su lugar el fomrato %lf
🖥️Epoch Time & time.h en C
⏳ Epoch Time
📌 Estándar de tiempo en Unix ➡️ Comienza: 1 enero 1970 – 00:00 hrs ➡️ Se mide en segundos transcurridos desde esa fecha ➡️ Sirve para:
📚 Biblioteca time.h
🔧 Herramienta para trabajar con tiempo en C
🛠️ Ejemplo básico
🔹 Incluir librerías
#include <stdio.h>
#include <time.h>
🔹 Declarar variable
time_t seconds;
🔹 Obtener tiempo actual
seconds = time(NULL);
🔹 Mostrar en horas
printf("Horas desde Epoch: %ld\n", seconds / 3600);
⚡ Medir rendimiento de un código
1️⃣ Definir variables
time_t begin, end;
2️⃣ Capturar inicio
begin = time(NULL);
3️⃣ Proceso (ejemplo)
for(long i = 0; i < 1500000000; i++);
4️⃣ Capturar fin
end = time(NULL);
5️⃣ Calcular duración
printf("Duración: %.2f segundos", difftime(end, begin));
💡 Consejos rápidos
✔️ Usa ciclos pequeños en pruebas
✔️ Apóyate en difftime() para precisión
✔️ Vigila el uso de CPU en bucles grandes
porque como argumento de time es null???
Porque esa es la forma de indicarle a la función time() que exprese el tiempo actual en el momento que es invocada la función, tomando como referencia el tiempo que ha pasado desde la EPOCH time. Es como decirle que asuma el valor "default" lo cual lo hace un método confiable para obtener una referencia actual del tiempo. Esto también pasa con otras funciones, al usar NULL como argumento, estas funciones asumen el valor por defecto de modo que siempre obtienes el mismo comportamiento. Con time(NULL) es un poco diferente porque la cantidad de tiempo (indistintamente de qué unidad de medida uses) que retornará la función nunca será la misma porque este valor siempre está cambiando a medida que pasa el tiempo. Es algo confuso al principio pero recuerda que el tiempo es una abstracción humana por lo tanto solamente nosotros le damos sentido al mismo en base a unidades de medida arbitrariamente definidas.
no me queda claro como es la logica en el printf el %d %f %ld etc etc alguien me lo puede aclarar?
No entendí el primer programa =(
#include <stdio.h> #include <time.h> int main() { time_t seconds; seconds = time(NULL); // Tiempo desde el 1 de Enero de 1970 a las 00:00 printf("El numero de horas desde EPOCH 1ro de Enero de 1970 a las 00:00 es: %ld \n", seconds); }
time_t seconds: Creamos una variable que contendrá lo que queramos. Su tipo no es uno cualquiera como int o float, sino que es time_t (pero vamos, en la práctica se comporta como un int).seconds = time(NULL); A seconds le asignamos lo que retorne la función time(NULL);. La función time te devuelve el número de segundos que han pasado desde el 1 de Enero de 1970 a las 00:00 (razones históricas, lo sé).printf, pero en lugar de poner los segundos, lo dividimos entre 3600 para obtener ese tiempo en horas.sigo sin entender porque me arroja diferentes resulados que a los del profesor
Holaaa eso es porque se toma desde 1970 hasta la fecha actual, es decir, cuando el profesor hizo el curso habian transcurido 44 y pico mil horas, pero cunado tu hiciste el curos pasaron mas horas desde 1970, y por lo tanto, incrementaron. Yo tengo 46000 horas.
Fecha y hora de grabación según el siguiente programa es:
Fecha y hora de la clase: 2020-06-10 12:00:00
#define MEASURE_OF_OURS_IN_CLASS 442169 int main() { time_t time_from_unix_epoch_time; struct tm *time_info; char time_string[100]; // Obtener el tiempo en segundos desde la clase time_from_unix_epoch_time = MEASURE_OF_OURS_IN_CLASS*3600; // Convertir time_t a struct tm como hora local time_info = localtime(&time_from_unix_epoch_time); // Formatear la fecha y hora en una cadena personalizada strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", time_info); printf("Fecha y hora de la clase: %s\n", time_string); return 0; } ```*#define* *MEASURE\_OF\_OURS\_IN\_CLASS* 442169int *main*() { *time\_t* time\_from\_unix\_epoch\_time; struct *tm* \*time\_info; char time\_string\[100];   *// Obtener el tiempo en segundos desde la clase* time\_from\_unix\_epoch\_time = *MEASURE\_OF\_OURS\_IN\_CLASS*\*3600;    *// Convertir time\_t a struct tm como hora local* time\_info = *localtime*(\&time\_from\_unix\_epoch\_time);   *// Formatear la fecha y hora en una cadena personalizada* *strftime*(time\_string, sizeof(time\_string), "%Y-%m-%d %H:%M:%S", time\_info); *printf*("Fecha y hora de la clase: %s\n", time\_string);   *return* 0;}
Muy buen aporte
Aquí dejo mi solución al reto.
#include <stdio.h> #include <time.h> int main() { time_t now = time(NULL); struct tm localTime = *localtime(&now); char formattedDate[20]; char format[] = "%Y-%m-%d %H:%M:%S"; int writedBytes = strftime(formattedDate, sizeof formattedD ate, format, &localTime); if (writedBytes != 0) { printf("La fecha actual es: %s\n", formattedDate); } return 0; }
Reto completado! Sin embargo, hoy es domingo y me aparece 0 como dia de la semana. No se como cambiar esto. Intente con IF y con WHILE pero no lo logre.
/*El programa tiene que devolver la fecha, la hora, y el dia actual*/ #include <stdio.h> #include <time.h> #define COT (-5) int main() { time_t tiempo; struct tm *info; time(&tiempo); info = gmtime(&tiempo); printf("Retorne EPOCH con operador AND: %d, y con macro NULL: %d \n", time(&tiempo), time(NULL)); printf("Fecha actual del EPOCH UTC/GMT: %2d/%2d/%4d, hora: %2d:%02d:%02d, dia de la semana:%d \n", info->tm_mday, info->tm_mon, (info->tm_year)+1900, (info->tm_hour)%24, info->tm_min, info->tm_sec, info->tm_wday); printf("Fecha actual de Colombia UTC-5/GMT-5: %2d/%2d/%4d, hora: %2d:%02d:%02d, dia de la semana:%d \n", info->tm_mday, info->tm_mon, (info->tm_year)+1900, (info->tm_hour+COT)%24, info->tm_min, info->tm_sec, info->tm_wday); return 0; }
Captura: