Is there any way that I can get PERL to give me the elapsed time that it took to calculate something? I'm trying to make my algorithm for finding prime numbers more efficient, and obviously I can't tell the differences in the time it took to generate the list, so I need a way to say "List generated in X seconds".
Any help would be much appreciated.

8 Years
Discussion Span
Last Post by orwell84

You can try the Benchmark or Time::HiRes modules, they come with perl. Read the documentation and try a few things, if you get stuck post back.


Thanks very much. The only question I have is as to why it says that it took a negative number of wallclock seconds. The longer it takes, the lower the number, essentially. Do you know why this is?


The Benchmark documentation says:


Comparing eval'd strings with code references will give you inaccurate results: a code reference will show a slightly slower execution time than the equivalent eval'd string.

The real time timing is done using time(2) and the granularity is therefore only one second.

Short tests may produce negative figures because perl can appear to take longer to execute the empty loop than a short test; try:


The system time of the null loop might be slightly more than the system time of the loop with the actual code and therefore the difference might end up being < 0.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.