Si calculan el EPOCH time actual y le restan el de la clase, podrían saber que día se grabo el curso. 🤯
Introducción a las funciones en C
Lo que aprenderás sobre funciones en C
¿Qué es una función en C?
Cómo usar las funciones
Tipos de retorno en funciones
Manejo de funciones en C
Implementación de funciones
Parámetros por valor
Bibliotecas estándar de funciones
Principales Bibliotecas de C
Math.h
String.h
Time.h
Stdlib.h
Cierre
Conclusiones
No tienes acceso a esta clase
¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera
El Epoch Time es un concepto fascinante y fundamental en la programación. Define un estándar temporal que todos los programas deben seguir, comenzando el 1 de enero de 1970 a las 00:00 horas. Esta fecha, decidida arbitrariamente, ha resultado invaluable para mantener la coherencia en el manejo del tiempo y la fecha en sistemas computacionales. Aunque nosotros, los humanos, medimos el tiempo en horas, días y años, en el mundo de la computación se mide en ciclos de procesamiento. Esta uniformidad ayuda a calcular tiempos específicos dentro del ámbito del procesamiento, así como en programación en general. Para manejar estas mediciones en C, utilizamos la biblioteca time.h
.
Al programar en C, la biblioteca time.h
es indispensable para manejar instrucciones relacionadas con el tiempo. Vamos a ver cómo utilizar esta biblioteca con un ejemplo básico de código.
Incluir las bibliotecas necesarias: Asegúrate de incluir las bibliotecas stdio.h
y time.h
.
#include <stdio.h>
#include <time.h>
Declaración de la variable de tiempo: Define una variable para almacenar el tiempo tipo time_t
.
time_t seconds;
Obtener el tiempo actual en Epoch: Usa la función time()
, pasándole un NULL
, para obtener el tiempo actual en segundos desde Epoch.
seconds = time(NULL);
Impresión de horas desde Epoch: Divide los segundos obtenidos entre 3600 para convertirlos en horas. Utiliza %ld
en printf
para manejar el tipo long
.
printf("El número de horas desde Epoch es %ld\n", seconds / 3600);
Compilar y ejecutar: Guarda el archivo como time.c
, compílalo y ejecuta para ver cuántas horas han pasado desde el 1 de enero de 1970.
time_t: Es una definición de tipo que se utiliza para guardar una representación de tiempo como un número entero que cuenta los segundos desde la fecha Epoch.
Function time(): Devuelve el tiempo actual basado en Epoch tomando NULL
como argumento, lo que permite obtener snapshots del tiempo actual.
En programación, es común necesitar medir cuánto tiempo tarda un código en ejecutarse. Veamos un ejemplo con un apuntador al uso de time.h
para obtener esta diferencia.
Reutiliza el código base: Copia el código anterior en un nuevo archivo, por ejemplo, time_diff.c
.
Define el inicio y fin del tiempo: Utiliza dos variables time_t
para registrar el comienzo y finalización del proceso.
time_t begin, end;
Captura el tiempo de inicio: Antes de un proceso pesado, marca el inicio.
begin = time(NULL);
Ejemplo de ciclo para uso intensivo de CPU: Con un ciclo for
se simula un proceso que consume tiempo para medir la diferencia.
for(long i = 0; i < 1500000000; i++);
Captura el tiempo de finalización: Una vez que el proceso termine, captura el tiempo final.
end = time(NULL);
Calcula y muestra el tiempo de ejecución: Utiliza difftime()
para establecer cuántos segundos han transcurrido entre el inicio y el fin.
printf("El tiempo que duró nuestro ciclo es %.2f segundos", difftime(end, begin));
Este ejemplo ilustra cómo usar time.h
para medir tiempos de ejecución en un contexto real. Además, es importante ajustar la magnitud de los procesos simulados para evitar tiempos de espera prolongados.
Utilizar la biblioteca time.h
no solo te permite manejar el tiempo según tus necesidades, sino también optimizar el rendimiento de tus programas. Aquí algunos consejos prácticos:
Simplifica pruebas con variables menores: Cuando hagas pruebas de ejecución, comienza con tamaños de ciclos más pequeños y escala gradualmente según sea necesario.
Refina los cálculos: Usa difftime()
para restar directamente valores time_t
y obtener diferencias precisas.
Monitorea el uso de CPU: Utiliza el administrador de tareas de tu sistema para observar el consumo de recursos y evitar sobrecargar el CPU con números extremados en ciclos.
Si bien este mero esbozo inicial puede ser suficiente, te sugiero personalizar y expandir las funcionalidades según tus necesidades específicas usando todas las capacidades que ofrece time.h
. ¡Atrévete a explorar más y continúa tu aprendizaje profundo del tiempo en programación!
Aportes 29
Preguntas 4
Si calculan el EPOCH time actual y le restan el de la clase, podrían saber que día se grabo el curso. 🤯
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? 🕰
#include <stdio.h>
#include <time.h>
int main()
{
time_t now;
time(&now); //por referencias
printf("The date and time is: %s\n", ctime(&now));
return 0;
}
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
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.
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)
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?
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:
Al ejecutar el programa, ocupa el 100% de la CPU, cabe mencionar que estoy trabajando en una raspberry pi 4 con 8 GB de RAM.
Aquí está el reto completado. Si alguien puede decirme cómo poner 2 saltos de línea con \r sin que se repita el enter (\n) se lo agradecería.
#include <stdio.h>
#include <string.h>
#include <time.h>
int main() {
char monthyear[12];
char weekday[11];
char meridian[3];
time_t start_time = time(NULL);
for (;;) {
time_t current_time = time(NULL);
struct tm* year=(localtime(¤t_time)->tm_year+1900);
struct tm* monthnumber=localtime(¤t_time)->tm_mon+1;
struct tm* yearday=localtime(¤t_time)->tm_yday + 1;
struct tm* weeknumber=localtime(¤t_time)->tm_wday+1;
struct tm* monthday=localtime(¤t_time)->tm_mday;
struct tm* hours=localtime(¤t_time)->tm_hour;
struct tm* minutes=localtime(¤t_time)->tm_min;
struct tm* seconds=localtime(¤t_time)->tm_sec;
current_time -= start_time;
if (monthnumber == 1)
strcpy(monthyear, "Enero");
else if (monthnumber == 2)
strcpy(monthyear, "Febrero");
else if (monthnumber == 3)
strcpy(monthyear, "Marzo");
else if (monthnumber == 4)
strcpy(monthyear, "Abril");
else if (monthnumber == 5)
strcpy(monthyear, "Mayo");
else if (monthnumber == 6)
strcpy(monthyear, "Junio");
else if (monthnumber == 7)
strcpy(monthyear, "Julio");
else if(monthnumber == 8)
strcpy(monthyear, "Agosto");
else if (monthnumber == 9)
strcpy(monthyear, "Septiembre");
else if (monthnumber == 10)
strcpy(monthyear, "Octubre");
else if (monthnumber == 11)
strcpy(monthyear, "Noviembre");
else if (monthnumber == 12)
strcpy(monthyear, "Diciembre");
else
strcpy(monthyear, "MONTH ERROR");
if (weeknumber == 1)
strcpy(weekday, "Domingo");
else if (weeknumber == 2)
strcpy(weekday, "Lunes");
else if (weeknumber == 3)
strcpy(weekday, "Martes");
else if (weeknumber == 4)
strcpy(weekday, "Miércoles");
else if (weeknumber == 5)
strcpy(weekday, "Jueves");
else if (weeknumber == 6)
strcpy(weekday, "Viernes");
else if (weeknumber == 7)
strcpy(weekday, "Sábado");
else
strcpy(weekday, "WDAY ERROR");
if ((int)hours %24 >= 0 && (int)hours %24 < 12)
strcpy(meridian, "AM");
else if ((int)hours %24 >= 12 && (int)hours %24 < 24)
strcpy(meridian, "PM");
else
strcpy(meridian, "ER");
printf("\rLa fecha es: %s, %.2i de %s de %i, Mes %.2i, Día %.2i | Hora: %.2i:%.2i:%.2i %s | (Execution time: %li)", weekday, monthday, monthyear, year, monthnumber, yearday, hours, minutes, seconds, meridian, current_time);
fflush(stdout);
sleep(1);
}
return 0;
}
#include <stdio.h>
#include <time.h>
/*Queremos saber la fecha y hora actual e imprimirla en la consola*/
time_t t;
int main(){
struct tm *tm;
char dateAndHour [100];
t = time(NULL);
tm = localtime(&t);
strftime(dateAndHour, 100, "%d/%m/%Y y la hora es: %H:%M:%S", tm);
printf("Hoy es: %s\n", dateAndHour);
return 0;
}
Resultado en la consola:
Buenas peña.
Comparto un artículo con ejemplos sobre este tema, bastante completo.
Cómo convertirte en un señor del tiempo en C/C++ desde cero
Un saludo y gracias.
#include <stdio.h>
#include <time.h>
int main()
{
time_t cl_et = 442169 * 3600;
//Wed Jun 10 17:00:00 2020 - La fecha en que se grabo la clase
printf("Current time: %s", ctime(&cl_et));
return 0;
}
Cual es la diferencia entre printnf y cout y su homologo con scanf y cin, esto lo vi en el universidad pero no tengo clara la diferencia.
Quien mas descubrió que esta clase se grabo aproximadamente un 11 de Junio del 2020?
Solución.
#include <stdio.h>
#include <time.h>
time_t seconds;
long main()
{
seconds = time(NULL);
printf("La horas local calculada desde EPOCH es: %s", asctime(localtime(&seconds)));
return 0;
}```
Esta es la forma fácil:
#include <stdio.h>
#include <time.h>
int main () {
time_t now;
now = time (NULL);
printf("This prorgam has written at: %s", ctime(&now));
}
Yo hubiera ido al administrador de tareas a cortar el proceso, no sabia que solo cerrando la consola de vsc se cancelaba el proceso
buena clase
#include <stdio.h>
#include <time.h>
int main()
{
time_t tiempo;
time(&tiempo);
printf("%s\n", ctime(&tiempo));
return 0 ;
}```
Un atajo a Save As es:
Alt + Shit + S
simple pero ahorra mucho tiempo
¿Quieres ver más aportes, preguntas y respuestas de la comunidad?