HOUSTON (KIAH) — Over half of adults in the U.S. drink coffee daily, but drinking a cup of Joe too close to bedtime could keep you from getting enough Zs.

A team of researchers in Scotland looked at how late in the day you can drink coffee without worrying about all that caffeine keeping you up at night.

The answer is to stop consuming caffeine six hours before bed. After that, it can mess with your internal clock.

“Caffeine is consumed daily by roughly 80% of the world’s population, often for its benefits in promoting wakefulness and concentration,” lead author of the study, Reneta Riha, said in a release. “Its effects can last for several hours.”

According to the study, the sleep-wake cycle — the circadian rhythm — regulates body functions relative to a 24-hour cycle. This rhythm syncs with Earth’s light and dark cycles, which is why time zone or work schedule changes can throw people out of whack.

The study also found that drinking four to five cups of coffee a day is generally fine as long as you stop early enough. Of course, that depends on how quickly or slowly people metabolize caffeine, so keep that in mind.

“Those who find that drinking coffee later in the day disrupts their sleep patterns may wish to swap to low caffeine drinks, or decaffeinated coffee during the afternoon and evening,” Riha said.

A previous study found that consuming 300 mg of caffeine each day — about three cups of coffee — can help improve cognition during the first three days of poor sleep, though researchers say a negative impact later on sleep quality and duration is likely.