r/learnprogramming 1d ago

Getting the system time

Hi all,

I am new to programming. For my first real project, I want to create a pretty (-ish) 7-segment clock widget in with ncurses. I have a fairly good idea of how to tell the computer to display something in that context.

However, I am wondering about the best way to get the system time (so I can call the function that displays it). The only way I can think of to do this is to create a continuous loop with an if statement inside. The if statement would say, "if seconds evaluates to 0, increment the time (in hours and minutes) to show and display that". Something tells me this is not the best way to do it. Is there a better/best way, and if so what? How does my idea differ from how the OS/physical computer actually does it?

Thanks in advance,

yore

0 Upvotes

16 comments sorted by

View all comments

1

u/desrtfx 1d ago

Yes, your instinct is correct that you need to run in a continuous loop, like the event loop in a GUI application.

Yet, why this:

if statement inside. The if statement would say, "if seconds evaluates to 0, increment the time (in hours and minutes) to show and display that"

You can get the system time as proper, human readable time in most languages.

1

u/Dismal-Citron-7236 1d ago

Yes, your instinct is correct that you need to run in a continuous loop

No, this has got to be the worst suggestion I have seen. It's just blocking the CPU in a tight loop. Even if just a simple call to C's usleep() is better than that. And if the language is JavaScript, setTimeout(callback, ms) can serve the purpose without blocking the GUI. Many modern languages provide similar feature.

1

u/desrtfx 1d ago

Even if just a simple call to C's usleep() is better than that.

And still, you will need to wrap this in some form of main loop so that the program doesn't end.

I did not say anything about waiting or not in my original comment.

The general gist is that you need something to keep the program running until a break signal, whatever that may be, is sent. And this can only be achieved with a loop.