When you’re pulling long hours and need to stay awake, a few Rip Its or a CamelBak’s worth of coffee feels like a must.

But new research can help show people exactly how much caffeine to consume and exactly when to consume it for maximum effectiveness.

The study, from the Army Medical Research and Materiel Command in Maryland, proposed an algorithm that identifies safe and effective caffeine-dosing strategies to help keep someone awake under any sleep-loss condition, according to a news release.

“We found that by using our algorithm, which determines when and how much caffeine a subject should consume, we can improve alertness by up to 64 percent, while consuming the same total amount of caffeine,” principal investigator and senior author Jaques Reifman said in the release.

Reifman, a research scientist, said someone can reduce his or her caffeine consumption by up to 65 percent and still feel improvements in alertness.

The study’s model predicts the effects of sleep loss and caffeine on psychomotor vigilance task performance — basically, your reaction time.

Researchers combined that model with a computer algorithm to determine when and how much caffeine to consume to (safely) maximize alertness during sleep loss, the release said.

This algorithm takes a user-provided sleep/wake schedule and maximum allowed caffeine as inputs and creates a caffeine-dosing strategy as the output.

“Our algorithm is the first quantitative tool that provides automated, customized guidance for safe and effective caffeine dosing to maximize alertness at the most needed times during any sleep-loss condition,” Reifman said.

The work was sponsored by Military Operational Medicine Program Area Directorate of the Army Medical Research and Materiel Command at Fort Detrick, Maryland. The study was published in the Journal of Sleep on May 28.