http://www.perlmonks.org?node_id=291821


in reply to Use time() to create unique ID

There are many ways round this without having to resort to a sleep - the most obvious being Time::HiRes, which (although system-dependant) will give you a much higher resolution than time().

Another way is to add a counter variable, something like (untested)...

my %idcount; my @ids; for (0..5){ my $t=time(); push @ids, $t."-".++$idcount{$t}; }
...resulting in "12345678-1","12345678-2" etc.

Cheers, Ben.

Replies are listed 'Best First'.
Re: Re: Use time() to create unique ID
by graff (Chancellor) on Sep 17, 2003 at 05:43 UTC
    Of all the stuff I've seen on the current thread, this idea seems easiest and most sensible. And if there were going to be multiple instances of the same script running at once, all you need to do is add the pid ($$) to the file name as well.

    Another way to avoid name collisions is to work out a unique name in a loop like this:

    ... my $append = "a"; while ( -e $id[$i] ) { $id[$i] =~ s/(?:\.[a-z]+)*$/.$append/; $append++; } `touch $id[$i]`; ...
    Use a separate semaphore file to lock up this part, if necessary, to avoid race conditions among concurrent jobs. But this is probably overkill for the OP's task (and it takes more overhead -- without adding any real value -- relative to the simple time.pid.incrementer, which would only risk collision if concurrent processes were writing to one shared directory from different hosts, and happened to have the same pids at the same time -- wow, how unlikely is that?).

      <voice id="Lt.Cmdr Data"> The odds are approximately 3,279,967,300,002 to 1</voice>

      <voice id="Q"> You humans have such a limited concept of space and time! You didn't allow for alternate unverses where what you term "Quantum Mechanics" is the everyday norm</voice>

      <voice id="Major S. Carter">Wouldn't we'd also have to consider the effects of parallel universes?</voice>

      <voice ID="Albert Einstein">And to tink zey laughed at my theoriezzzz.</voice>

      <voice ID="Stephen Hawkin">The- whole - thing - can - be - easily - visualised - in -terms - of - the - likelyhood - of - two - billard - balls - dropping - into - the - same - pocket - at - the - same - time - from - the - breakoff.</voice>

      <voice ID="Z. Beedlebrox">Now if only we could make the destination of the Infinite Probablity Drive a little more predicable..</voice>


      Examine what is said, not who speaks.
      "Efficiency is intelligent laziness." -David Dunham
      "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller
      If I understand your problem, I can solve it! Of course, the same can be said for you.