8

I'm trying to convert seconds to milliseconds (or microseconds) without dividing by 1,000 or 1,000,000. The reason I'm doing it is because I don't want the decimal point to be shown. Is there a way of showing milliseconds or microseconds without the decimal point and without dividing by 1,000 or 1,000,000?

Here's my code with method execution timing:

from random import randint list = [1]*1000 for i in range (1, 1000): list[i] = randint(1,100) def insertion(list): for index in range(1,len(list)): value = list[index] i = index - 1 while i>=0 and (value < list[i]): list[i+1] = list[i] list[i] = value i = i - 1 def test(): start = time.clock() insertion(list) elapsed = (time.clock() - start) print "Time taken for insertion = ", elapsed if __name__ == '__main__': import time test() 
4
  • 6
    1 second is 1000 milliseconds, so you need to multiply. Commented Apr 30, 2013 at 17:40
  • 1
    To time algorithms, use the timeit module. Commented Apr 30, 2013 at 17:41
  • If the only constraint is that you don't want the decimal point to be shown, you can just print it with a format that doesn't show the decimal point. For example: print "Time taken for insertion = {:.0f}".format(elapsed). Then it doesn't matter what type you have. Commented Apr 30, 2013 at 17:50
  • And meanwhile, in Python 2.7 and earlier, if n is an int, n / 1000 is an int too (unless you use a __future__ statement). If you want to be absolutely sure, use the explicit "floordiv" operator: n // 1000 is an int even in 3.x. Commented Apr 30, 2013 at 17:52

2 Answers 2

12

Sure! To convert seconds to milliseconds or microseconds, you multiply by the number of the desired divisions in a second (e.g. 1000 for milliseconds). No division needed!

If you don't want the decimal places, use round() or int() on the result.

Sign up to request clarification or add additional context in comments.

2 Comments

Why wouldn't you divide? 1000th of a second is millisecond, right?
@wizardo: you want to convert seconds to milliseconds. 1 second is 1000 milliseconds. 0.001 seconds is 1 millisecond. You multiply by 1000 to go from seconds to milliseconds.
7

I think your question may be missing something. To convert an amount of seconds to milliseconds, you can simply multiply (not divide) by 1000.

If it's 52 seconds:

52 * 1000 

This would return the integer 52000.

Comments