42_Philosopher/philo/time.c

52 lines
1.7 KiB
C
Raw Permalink Normal View History

2023-04-27 08:05:14 -04:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* time.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angouleme.fr +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/04/27 11:35:26 by cchauvet #+# #+# */
2023-05-25 11:31:02 -04:00
/* Updated: 2023/05/25 17:28:19 by cchauvet ### ########.fr */
2023-04-27 08:05:14 -04:00
/* */
/* ************************************************************************** */
2023-04-13 09:00:39 -04:00
#include <bits/types/struct_timeval.h>
#include <sys/time.h>
#include <stddef.h>
#include <pthread.h>
2023-04-27 08:05:14 -04:00
#include "./philo.h"
#include "data.h"
2023-04-13 09:00:39 -04:00
size_t get_time(void)
{
size_t time;
2023-04-19 10:08:23 -04:00
static size_t start_time = 0;
2023-04-13 09:00:39 -04:00
struct timeval tv;
2023-04-27 08:05:14 -04:00
2023-04-13 09:00:39 -04:00
gettimeofday(&tv, NULL);
time = tv.tv_sec * 1000000 + tv.tv_usec;
2023-04-19 10:08:23 -04:00
if (start_time == 0)
start_time = time;
return ((time - start_time) / 1000);
2023-04-13 09:00:39 -04:00
}
2023-04-27 08:05:14 -04:00
size_t get_time_eat(t_philo *philo, t_data *data)
2023-04-27 08:05:14 -04:00
{
size_t time;
time = get_time();
2023-05-25 11:31:02 -04:00
if (time + data->eat_time > data->life_expectency + philo->last_eat)
return (data->life_expectency + philo->last_eat - time);
return (data->eat_time);
2023-04-27 08:05:14 -04:00
}
size_t get_time_sleep(t_philo *philo, t_data *data)
{
size_t time;
time = get_time();
2023-05-25 11:31:02 -04:00
if (time + data->sleep_time > data->life_expectency + philo->last_eat)
return (data->life_expectency + philo->last_eat - time);
return (data->sleep_time);
}