philosophers_prep/rendu/precise_timing.c

52 lines
1.7 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* precise_timing.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ruiferna <ruiferna@student.42porto.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/10/07 20:17:52 by ruiferna #+# #+# */
/* Updated: 2025/10/07 20:49:11 by ruiferna ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
long long get_current_time()
{
struct timeval tv;
gettimeofday(&tv,NULL);
/*
A stuct tv tem tv_sec que sao os segundos desde a epoch e temos a tv_usec
que retorna os microsegundos ate completar 1 segundo (um milhão de microssegundos = 1 segundo).
Por isso, para conseguirmos realmente medir os milisegundos precisamos de juntar os dois
*/
return ((tv.tv_sec * 1000LL) + (tv.tv_usec / 1000LL));
}
long long time_diff(long long start, long long end)
{
return (end - start);
}
void precise_sleep(int ms)
{
long long start_time;
start_time = get_current_time();
while ((get_current_time() - start_time) < ms)
{
usleep(100);
}
}
int main()
{
long long start = get_current_time();
precise_sleep(100);
long long end = get_current_time();
printf("Time difference: %lld ms", time_diff(start, end));
return (0);
}