I wrote the following programs to compare the speed of python with c/fortran. To get the time used by the programs I used the \"time\" command. All the programs compute the sq
for calculations i might try haskell or ml...
try this code in ML:
fun trip(x,y,z) = if y=z then 0
else trip(((Math.sqrt((1.0*1.0)+(2.0*2.0)+(3.0*3.0)))*1.0),(y+1),z);
trip(1.0,1,300000000);
probably you can. There are a number of math libraries for python which probably can do the task you want quite a bit more efficient. Since the python ranges work quite different than c loops, I would try to unroll these loops first.
Flawed benchmark.
If you want to time floating point arithmetic, then you should first time the loops doing nothing (or as close to nothing as you can manage). To avoid optimizing away the whole loop, make sure it is doing something like moving a single byte char from one array to another.
Then time it again with the floating point calculation and subtract the first timing to get a more accurate number.
Also, Python only has double floating point numbers so a more even test would ensure that the other languages also use floating point. And as others have mentioned, Python is widely used for scientific computing but those scientists generally use the numpy library to do matrix calculations rather than writing Python loops.
As a rule, numpy is used for scientific calculations in python. You probably should test that lib.
You have not explained exactly what the goal of your measurement is, so it is very hard to answer whether or not your test code is going to adequately provide you with information to satisfy that goal. In general, benchmarks exist to tell you something very specific -- you should know exactly what you're trying to figure out by conducting the benchmark. Microbenchmarks, of the type you're trying above, are also notorious for providing distorted answers...
Be aware that the calculation of r
does not depend on the loop variables, so an optimizing compiler may move the calculation out of the loop, and just run the empty loop for the requested number of times; or even remove that loop completely and only do the calculation of the square root.
A real smart optimizer may notice that you're not doing anything with the result, so the complete program may be optimized away without altering the output (i.e. nothing).