I've made this simple timer/alarm for myself for this game I'm playing. I want to use it to inform me of an automated event a few minutes before it happens. It isn't done yet, but I am concerned with how much resources it takes. From the compiler, it takes about 20% CPU which is disturbing for me since the game itself only takes about 10%.

Again, the code is by all means not yet done but all it takes now is a simple condition. I want to know if there is any way I can make it more efficient.

#include<stdio.h>
#include<time.h>
#include<stdlib.h>

int main(void){
    time_t server_time;
    struct tm server;
    char server_str[50];
    int i = 0, temp, min_temp = 0;

    server_time = time(NULL) - (5 * 60 * 60);

    server = *(gmtime(&server_time));

    strftime(server_str, 50, "%A, %B %d %Y", &server);

    temp = server.tm_sec;
    while(i == 0){
        server_time = time(NULL) - (5 * 60 * 60);
        server = *(gmtime(&server_time));
        if(temp != server.tm_sec){
            system("cls");
            printf("SERVER TIME: (%s) (%02d:%02d:%02d)\n", server_str, server.tm_hour, server.tm_min, server.tm_sec);
            temp = server.tm_sec;
        }
        if(server.tm_hour == 7 || server.tm_hour == 15 || server.tm_hour == 23){
            //if(server.tm_min > 56){
             //   min_temp =
            //}
        }
    };
}

A proper timer will put the thread to sleep and allow context switching. Your naive timer doesn't release the thread and simply eats up CPU cycles doing nothing. This is precisely why the busy wait style of timing is undesirable. There's not really a good way to efficiently use time slices without moving to a more appropriate timer implementation.

I kind of realized that half way through it, but I had no idea on how to do it better. Can you suggest any? I would like to do this better.

Well, at this point you're entering the realm of non-portable features. But it's often a safe assumption to support both Windows and POSIX, then call it good:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#ifdef _WIN32
#include <windows.h>

#define sleep(x) Sleep(x * 1000)
#define clear "cls"
#else
#include <unistd.h>

#define clear "clear"
#endif

int main(void)
{
    const int seconds = 5;

    while (1) {
        char buf[BUFSIZ];
        time_t now = time(NULL);

        system(clear);
        
        if (strftime(buf, sizeof buf, "SERVER TIME: %H:%M:%S", gmtime(&now)) != 0)
            puts(buf);

        sleep(seconds);
    }
}

Wow... Thank you very much. I was totally unaware of Sleep() nor windows.h. It doesn't even register on my Task Manager now.

And you need not sleep 5 seconds, you can count how many seconds is left to alarm and not do loop at all, only one sleep, if time does not need super accurate.

This article has been dead for over six months. Start a new discussion instead.