Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert milliseconds to seconds in C

Tags:

c

time

Simple C question, how can I correctly and succintly convert milliseconds to seconds. There are two constraints:

  • I've no floating point support in this tiny subset-of-C compiler
  • I need the seconds rounded to the nearest second(1-499ms rounds down,500-999ms rounds up. Don't need to care about negative values)

    int mseconds = 1600; // should be converted to 2 seconds
    int msec = 23487;  // should be converted to 23 seconds
    
like image 795
leeeroy Avatar asked Aug 18 '09 16:08

leeeroy


People also ask

How do you convert milliseconds to minutes and seconds?

Convert Milliseconds to minutes using the formula: minutes = (milliseconds/1000)/60). Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60).

How do you convert milliseconds to time?

To convert a second measurement to a millisecond measurement, multiply the time by the conversion ratio. The time in milliseconds is equal to the seconds multiplied by 1,000.

How do you convert milliseconds to hours minutes seconds?

To convert milliseconds to hours, minutes, seconds:Divide the milliseconds by 1000 to get the seconds. Divide the seconds by 60 to get the minutes. Divide the minutes by 60 to get the hours. Add a leading zero if the values are less than 10 to format them consistently.

What is MS in time unit?

A millisecond (ms or msec) is one thousandth of a second and is commonly used in measuring the time to read to or write from a hard disk or a CD-ROM player or to measure packet travel time on the Internet. For comparison, a microsecond (us or Greek letter mu plus s) is one millionth (10-6) of a second.


2 Answers

This should work

int sec = ((msec + 500) / 1000);
like image 113
Chi Avatar answered Oct 13 '22 14:10

Chi


int seconds = msec / 1000;
if (msec % 1000 > 500)
    seconds++;
like image 44
qrdl Avatar answered Oct 13 '22 14:10

qrdl