Using System Time to Generate Unique Seeds
A pseudo-random number generator (PRNG) produces the same sequence of numbers when given the same seed. While this reproducibility is useful for debugging and testing, many applications require different sequences on each run. By seeding with the current system time, we get a unique starting point for each program execution.
Fixed seeds produce identical sequencesβessential for scientific reproducibility and debugging.
Time-based seeds ensure different results each runβideal for simulations, games, and sampling.
Higher resolution time sources (milliseconds, nanoseconds) reduce the chance of seed collisions.
Seeds must be positive integers less than m (2,147,483,647) for the Park-Miller algorithm.
Time-based seeding is not suitable for cryptographic applications. The seed can be guessed if an attacker knows approximately when the program started. For security-sensitive applications, use a cryptographically secure random number generator (CSPRNG) provided by your operating system.
Park, S.K. and Miller, K.W. (1988). "Random Number Generators: Good Ones Are Hard to Find." Communications of the ACM, Vol. 31, No. 10, pp. 1192-1201.
Implementation & Tutorial: Andrew J. Pounds, Ph.D.
Departments of Chemistry and Computer Science, Mercer University
Using system_clock() and date_and_time() intrinsics
system_clock(count) β Returns processor clock ticks since an arbitrary point (high resolution)
date_and_time(values) β Returns current date/time in an 8-element array
Fortran provides two primary methods for obtaining time-based seeds. The system_clock
intrinsic offers higher resolution, while date_and_time provides human-readable components
that can be combined into a seed.
! =============================================================================
! Park-Miller Minimal Standard Random Number Generator
! Module with Time-Based Seeding Support
!
! Adapted from: Park, S.K. & Miller, K.W. (1988)
! "Random Number Generators: Good Ones Are Hard to Find"
! Communications of the ACM, Vol. 31, No. 10, pp. 1192-1201
!
! Implementation by Andrew J. Pounds, Ph.D.
! Departments of Chemistry and Computer Science
! Mercer University
! =============================================================================
module random_module
implicit none
! Algorithm constants
real(kind=8), parameter :: A = 16807.0D0
real(kind=8), parameter :: M = 2147483647.0D0
contains
! -------------------------------------------------------------------------
! Generate a pseudo-random number in the range (0, 1)
! -------------------------------------------------------------------------
real(kind=8) function random(seed)
real(kind=8), intent(inout) :: seed
real(kind=8) :: temp
temp = A * seed
seed = temp - M * int(temp / M)
random = seed / M
end function random
! -------------------------------------------------------------------------
! Get seed from system_clock (high resolution)
! -------------------------------------------------------------------------
subroutine get_time_seed_clock(seed)
real(kind=8), intent(out) :: seed
integer :: count, count_rate, count_max
! Get current clock count
call system_clock(count, count_rate, count_max)
! Convert to valid seed (ensure positive and within range)
seed = dble(mod(abs(count), 2147483646)) + 1.0D0
end subroutine get_time_seed_clock
! -------------------------------------------------------------------------
! Get seed from date_and_time (combines date/time components)
! -------------------------------------------------------------------------
subroutine get_time_seed_datetime(seed)
real(kind=8), intent(out) :: seed
integer :: values(8)
integer(kind=8) :: combined
! Get current date and time
! values: year, month, day, timezone, hour, minute, second, millisecond
call date_and_time(values=values)
! Combine components into a single seed value
combined = values(8) ! milliseconds
combined = combined + values(7) * 1000 ! seconds
combined = combined + values(6) * 60000 ! minutes
combined = combined + values(5) * 3600000 ! hours
combined = combined + values(3) * 86400000 ! days
! Ensure valid seed range
seed = dble(mod(combined, 2147483646_8)) + 1.0D0
end subroutine get_time_seed_datetime
end module random_module
! =============================================================================
! Demonstration: Time-Based Seeding for Park-Miller RNG
!
! Andrew J. Pounds, Ph.D.
! Departments of Chemistry and Computer Science
! Mercer University
! =============================================================================
program random_time_demo
use random_module
implicit none
real(kind=8) :: seed1, seed2
real(kind=8) :: r
integer :: i
integer :: dt_values(8)
print '(A)', '=============================================='
print '(A)', ' Park-Miller RNG: Time-Based Seeding'
print '(A)', ' Fortran 90 Implementation'
print '(A)', '=============================================='
print '(A)', ''
! Display current date and time
call date_and_time(values=dt_values)
print '(A, I4, A, I2.2, A, I2.2, A, I2.2, A, I2.2, A, I2.2, A, I3.3)', &
'Current time: ', dt_values(1), '-', dt_values(2), '-', dt_values(3), &
' ', dt_values(5), ':', dt_values(6), ':', dt_values(7), '.', dt_values(8)
print '(A)', ''
! Method 1: Using system_clock
print '(A)', 'Method 1: Seed from system_clock()'
print '(A)', '----------------------------------------------'
call get_time_seed_clock(seed1)
print '(A, F15.1)', 'Generated seed: ', seed1
print '(A)', ''
print '(A)', 'Random numbers:'
do i = 1, 5
r = random(seed1)
print '(A, I2, A, F12.10)', ' Random #', i, ': ', r
end do
print '(A)', ''
! Method 2: Using date_and_time
print '(A)', 'Method 2: Seed from date_and_time()'
print '(A)', '----------------------------------------------'
call get_time_seed_datetime(seed2)
print '(A, F15.1)', 'Generated seed: ', seed2
print '(A)', ''
print '(A)', 'Random numbers:'
do i = 1, 5
r = random(seed2)
print '(A, I2, A, F12.10)', ' Random #', i, ': ', r
end do
print '(A)', '----------------------------------------------'
print '(A)', 'Run again to see different sequences!'
end program random_time_demo
gfortran -o random_time_demo random_module.f90 random_time_demo.f90./random_time_demo==============================================
Park-Miller RNG: Time-Based Seeding
Fortran 90 Implementation
==============================================
Current time: 2024-01-15 14:32:07.542
Method 1: Seed from system_clock()
----------------------------------------------
Generated seed: 847362951.0
Random numbers:
Random # 1: 0.6628417532
Random # 2: 0.2314589076
Random # 3: 0.8891234567
Random # 4: 0.4523178904
Random # 5: 0.1098765432
----------------------------------------------
Method 2: Seed from date_and_time()
----------------------------------------------
Generated seed: 1234567890.0
Random numbers:
Random # 1: 0.3847562190
Random # 2: 0.7123456789
Random # 3: 0.0567891234
Random # 4: 0.9234567801
Random # 5: 0.2890123456
----------------------------------------------
Run again to see different sequences!
Note: Your output will differ based on the current time.
Using get-universal-time and get-internal-real-time
(get-universal-time) β Seconds since January 1, 1900 (integer)
(get-internal-real-time) β Implementation-dependent high-resolution time
Common Lisp offers get-universal-time for portable second-resolution time and
get-internal-real-time for higher resolution (implementation-dependent). We combine
these for better seed uniqueness.
;;;; =============================================================================
;;;; Park-Miller RNG with Time-Based Seeding
;;;; Common Lisp Implementation for SBCL
;;;;
;;;; Adapted from: Park, S.K. & Miller, K.W. (1988)
;;;; "Random Number Generators: Good Ones Are Hard to Find"
;;;; Communications of the ACM, Vol. 31, No. 10, pp. 1192-1201
;;;;
;;;; Implementation by Andrew J. Pounds, Ph.D.
;;;; Departments of Chemistry and Computer Science
;;;; Mercer University
;;;; =============================================================================
(defconstant +a+ 16807.0d0
"Multiplier constant for Park-Miller algorithm")
(defconstant +m+ 2147483647.0d0
"Modulus constant (2^31 - 1)")
(defconstant +max-seed+ 2147483646
"Maximum valid seed value")
;;; ---------------------------------------------------------------------------
;;; Time-based seed generation
;;; ---------------------------------------------------------------------------
(defun get-time-seed-universal ()
"Generate a seed from universal time (seconds since 1900-01-01).
Simple but only second resolution."
(let ((time (get-universal-time)))
(1+ (mod time +max-seed+))))
(defun get-time-seed-internal ()
"Generate a seed from internal real time (higher resolution).
Resolution depends on internal-time-units-per-second."
(let ((time (get-internal-real-time)))
(1+ (mod time +max-seed+))))
(defun get-time-seed-combined ()
"Generate a seed by combining universal and internal time.
Provides better uniqueness than either alone."
(let* ((universal (get-universal-time))
(internal (get-internal-real-time))
(combined (logxor (* universal 1000) internal)))
(1+ (mod (abs combined) +max-seed+))))
;;; ---------------------------------------------------------------------------
;;; Random number generator
;;; ---------------------------------------------------------------------------
(defun make-random-generator (&optional seed)
"Create a random number generator.
If seed is nil, uses time-based seeding."
(let ((current-seed (coerce (or seed (get-time-seed-combined))
'double-float)))
(format t "Initialized with seed: ~A~%" (floor current-seed))
(lambda ()
(let ((temp (* +a+ current-seed)))
(setf current-seed (- temp (* +m+ (floor temp +m+))))
(/ current-seed +m+)))))
(defun park-miller-random (seed)
"Single-shot random: returns (values random-number new-seed)"
(let* ((seed-float (coerce seed 'double-float))
(temp (* +a+ seed-float))
(new-seed (- temp (* +m+ (floor temp +m+)))))
(values (/ new-seed +m+) new-seed)))
;;; ---------------------------------------------------------------------------
;;; Demonstration
;;; ---------------------------------------------------------------------------
(defun format-current-time ()
"Format current time as a readable string"
(multiple-value-bind (sec min hour day month year)
(decode-universal-time (get-universal-time))
(format nil "~4D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D"
year month day hour min sec)))
(defun main ()
(format t "~%==============================================")
(format t "~% Park-Miller RNG: Time-Based Seeding")
(format t "~% Common Lisp Implementation")
(format t "~%==============================================~%")
(format t "~%Current time: ~A~%" (format-current-time))
(format t "Internal time units per second: ~A~%"
internal-time-units-per-second)
;; Method 1: Universal time seed
(format t "~%Method 1: Seed from get-universal-time~%")
(format t "----------------------------------------------~%")
(let* ((seed (get-time-seed-universal))
(rng (make-random-generator seed)))
(format t "~%Random numbers:~%")
(dotimes (i 5)
(format t " Random #~2D: ~12,10F~%" (1+ i) (funcall rng))))
;; Method 2: Internal time seed
(format t "~%Method 2: Seed from get-internal-real-time~%")
(format t "----------------------------------------------~%")
(let* ((seed (get-time-seed-internal))
(rng (make-random-generator seed)))
(format t "~%Random numbers:~%")
(dotimes (i 5)
(format t " Random #~2D: ~12,10F~%" (1+ i) (funcall rng))))
;; Method 3: Combined seed (recommended)
(format t "~%Method 3: Combined time seed (recommended)~%")
(format t "----------------------------------------------~%")
(let ((rng (make-random-generator))) ; nil triggers time-based seed
(format t "~%Random numbers:~%")
(dotimes (i 5)
(format t " Random #~2D: ~12,10F~%" (1+ i) (funcall rng))))
(format t "----------------------------------------------~%")
(format t "Run again to see different sequences!~%"))
;; Run demonstration
(main)
random-time-seed.lispsbcl --script random-time-seed.lispsbcl --load random-time-seed.lisp==============================================
Park-Miller RNG: Time-Based Seeding
Common Lisp Implementation
==============================================
Current time: 2024-01-15 14:32:07
Internal time units per second: 1000000
Method 1: Seed from get-universal-time
----------------------------------------------
Initialized with seed: 3912847265
Random numbers:
Random # 1: 0.4521876543
Random # 2: 0.8932145678
Random # 3: 0.1234567890
Random # 4: 0.6789012345
Random # 5: 0.3456789012
Method 2: Seed from get-internal-real-time
----------------------------------------------
Initialized with seed: 1587423690
Random numbers:
Random # 1: 0.7891234567
Random # 2: 0.2345678901
Random # 3: 0.5678901234
Random # 4: 0.0123456789
Random # 5: 0.8901234567
Method 3: Combined time seed (recommended)
----------------------------------------------
Initialized with seed: 982736451
Random numbers:
Random # 1: 0.5432109876
Random # 2: 0.0987654321
Random # 3: 0.6543210987
Random # 4: 0.2109876543
Random # 5: 0.7654321098
----------------------------------------------
Run again to see different sequences!
Note: Your output will differ based on the current time.
Using SysUtils and DateUtils units
GetTickCount64 β Milliseconds since system boot (high resolution)
Now β Current date/time as TDateTime
MilliSecondOfTheDay β Milliseconds since midnight
Free Pascal's SysUtils and DateUtils units provide comprehensive
time functions. GetTickCount64 offers high resolution, while Now with
DateUtils provides flexible date/time manipulation.
{******************************************************************************
* Park-Miller RNG with Time-Based Seeding
* Pascal Implementation for Free Pascal Compiler
*
* Adapted from: Park, S.K. & Miller, K.W. (1988)
* "Random Number Generators: Good Ones Are Hard to Find"
* Communications of the ACM, Vol. 31, No. 10, pp. 1192-1201
*
* Implementation by Andrew J. Pounds, Ph.D.
* Departments of Chemistry and Computer Science
* Mercer University
******************************************************************************}
program RandomTimeDemo;
uses
SysUtils, DateUtils;
const
A: Double = 16807.0;
M: Double = 2147483647.0;
MaxSeed: Int64 = 2147483646;
var
Seed: Double;
{ --------------------------------------------------------------------------- }
{ Park-Miller random number generator }
{ --------------------------------------------------------------------------- }
function ParkMillerRandom: Double;
var
Temp: Double;
begin
Temp := A * Seed;
Seed := Temp - M * Trunc(Temp / M);
ParkMillerRandom := Seed / M;
end;
{ --------------------------------------------------------------------------- }
{ Get seed from system tick count (milliseconds since boot) }
{ --------------------------------------------------------------------------- }
function GetTimeSeedTick: Double;
var
Ticks: QWord;
begin
Ticks := GetTickCount64;
GetTimeSeedTick := (Ticks mod MaxSeed) + 1;
end;
{ --------------------------------------------------------------------------- }
{ Get seed from current date/time }
{ --------------------------------------------------------------------------- }
function GetTimeSeedDateTime: Double;
var
CurrentTime: TDateTime;
MilliSeconds: Int64;
Days: Int64;
Combined: Int64;
begin
CurrentTime := Now;
MilliSeconds := MilliSecondOfTheDay(CurrentTime);
Days := DaysBetween(CurrentTime, EncodeDate(2000, 1, 1));
Combined := (Days * 86400000) + MilliSeconds;
GetTimeSeedDateTime := (Abs(Combined) mod MaxSeed) + 1;
end;
{ --------------------------------------------------------------------------- }
{ Get seed by combining multiple time sources }
{ --------------------------------------------------------------------------- }
function GetTimeSeedCombined: Double;
var
Ticks: QWord;
MilliSeconds: Int64;
Combined: Int64;
begin
Ticks := GetTickCount64;
MilliSeconds := MilliSecondOfTheDay(Now);
Combined := (Ticks xor (MilliSeconds * 12345));
GetTimeSeedCombined := (Abs(Combined) mod MaxSeed) + 1;
end;
{ --------------------------------------------------------------------------- }
{ Main Program }
{ --------------------------------------------------------------------------- }
var
I: Integer;
R: Double;
begin
WriteLn('==============================================');
WriteLn(' Park-Miller RNG: Time-Based Seeding');
WriteLn(' Pascal Implementation');
WriteLn('==============================================');
WriteLn;
{ Display current date and time }
WriteLn('Current time: ', FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', Now));
WriteLn;
{ Method 1: Tick count seed }
WriteLn('Method 1: Seed from GetTickCount64()');
WriteLn('----------------------------------------------');
Seed := GetTimeSeedTick;
WriteLn('Generated seed: ', Seed:15:1);
WriteLn;
WriteLn('Random numbers:');
for I := 1 to 5 do
begin
R := ParkMillerRandom;
WriteLn(' Random #', I:2, ': ', R:12:10);
end;
WriteLn;
{ Method 2: DateTime seed }
WriteLn('Method 2: Seed from Now + MilliSecondOfTheDay()');
WriteLn('----------------------------------------------');
Seed := GetTimeSeedDateTime;
WriteLn('Generated seed: ', Seed:15:1);
WriteLn;
WriteLn('Random numbers:');
for I := 1 to 5 do
begin
R := ParkMillerRandom;
WriteLn(' Random #', I:2, ': ', R:12:10);
end;
WriteLn;
{ Method 3: Combined seed }
WriteLn('Method 3: Combined time seed (recommended)');
WriteLn('----------------------------------------------');
Seed := GetTimeSeedCombined;
WriteLn('Generated seed: ', Seed:15:1);
WriteLn;
WriteLn('Random numbers:');
for I := 1 to 5 do
begin
R := ParkMillerRandom;
WriteLn(' Random #', I:2, ': ', R:12:10);
end;
WriteLn('----------------------------------------------');
WriteLn('Run again to see different sequences!');
end.
random_time_demo.pasfpc random_time_demo.pas./random_time_demo==============================================
Park-Miller RNG: Time-Based Seeding
Pascal Implementation
==============================================
Current time: 2024-01-15 14:32:07.542
Method 1: Seed from GetTickCount64()
----------------------------------------------
Generated seed: 8472651903.0
Random numbers:
Random # 1: 0.3847291056
Random # 2: 0.7192834765
Random # 3: 0.0583746291
Random # 4: 0.4928173650
Random # 5: 0.8374629105
Method 2: Seed from Now + MilliSecondOfTheDay()
----------------------------------------------
Generated seed: 527384619.0
Random numbers:
Random # 1: 0.6291847305
Random # 2: 0.1738462910
Random # 3: 0.8462910574
Random # 4: 0.2910574839
Random # 5: 0.5748392016
Method 3: Combined time seed (recommended)
----------------------------------------------
Generated seed: 1938476251.0
Random numbers:
Random # 1: 0.9384762510
Random # 2: 0.4762510384
Random # 3: 0.0251038476
Random # 4: 0.5103847625
Random # 5: 0.7625103847
----------------------------------------------
Run again to see different sequences!
Note: Your output will differ based on the current time.
Using Ada.Calendar and Ada.Real_Time packages
Ada.Calendar.Clock β Current time as Time type
Ada.Calendar.Seconds β Seconds within the day
Ada.Real_Time.Clock β High-resolution monotonic time
Ada provides Ada.Calendar for wall-clock time and Ada.Real_Time for
high-resolution monotonic time. The latter is particularly useful for generating unique seeds
in rapid succession.
-------------------------------------------------------------------------------
-- Park-Miller RNG with Time-Based Seeding
-- Ada Package Specification
--
-- Adapted from: Park, S.K. & Miller, K.W. (1988)
-- "Random Number Generators: Good Ones Are Hard to Find"
-- Communications of the ACM, Vol. 31, No. 10, pp. 1192-1201
--
-- Implementation by Andrew J. Pounds, Ph.D.
-- Departments of Chemistry and Computer Science
-- Mercer University
-------------------------------------------------------------------------------
package Park_Miller_Time is
-- Generator type
type Generator is private;
-- Initialize with explicit seed
procedure Initialize (Gen : out Generator; Seed : in Long_Float);
-- Initialize with time-based seed (Calendar)
procedure Initialize_From_Calendar (Gen : out Generator);
-- Initialize with time-based seed (Real_Time - higher resolution)
procedure Initialize_From_Real_Time (Gen : out Generator);
-- Generate next random number
function Random (Gen : in out Generator) return Long_Float;
-- Get current seed value
function Get_Seed (Gen : in Generator) return Long_Float;
private
type Generator is record
Seed : Long_Float := 1.0;
end record;
end Park_Miller_Time;
-------------------------------------------------------------------------------
-- Park-Miller RNG with Time-Based Seeding
-- Ada Package Body
--
-- Implementation by Andrew J. Pounds, Ph.D.
-- Departments of Chemistry and Computer Science
-- Mercer University
-------------------------------------------------------------------------------
with Ada.Calendar;
with Ada.Real_Time;
package body Park_Miller_Time is
-- Algorithm constants
A : constant Long_Float := 16807.0;
M : constant Long_Float := 2147483647.0;
Max_Seed : constant Long_Float := 2147483646.0;
---------------------------------------------------------------------------
procedure Initialize (Gen : out Generator; Seed : in Long_Float) is
begin
Gen.Seed := Seed;
end Initialize;
---------------------------------------------------------------------------
procedure Initialize_From_Calendar (Gen : out Generator) is
use Ada.Calendar;
Now : Time := Clock;
Year : Year_Number;
Month : Month_Number;
Day : Day_Number;
Day_Seconds : Day_Duration;
Combined : Long_Float;
begin
Split (Now, Year, Month, Day, Day_Seconds);
Combined := Long_Float (Day_Seconds) * 1000.0 +
Long_Float (Day) * 86400000.0 +
Long_Float (Month) * 2678400000.0;
Gen.Seed := Long_Float'Remainder (abs (Combined), Max_Seed) + 1.0;
end Initialize_From_Calendar;
---------------------------------------------------------------------------
procedure Initialize_From_Real_Time (Gen : out Generator) is
use Ada.Real_Time;
Now : Time := Clock;
Span : Time_Span;
Seconds : Seconds_Count;
Fraction : Time_Span;
Nanos : Long_Float;
begin
Split (Now, Seconds, Fraction);
-- Convert to nanoseconds for high resolution
Nanos := Long_Float (Seconds) * 1_000_000_000.0 +
Long_Float (To_Duration (Fraction)) * 1_000_000_000.0;
Gen.Seed := Long_Float'Remainder (abs (Nanos), Max_Seed) + 1.0;
end Initialize_From_Real_Time;
---------------------------------------------------------------------------
function Random (Gen : in out Generator) return Long_Float is
Temp : Long_Float;
begin
Temp := A * Gen.Seed;
Gen.Seed := Temp - M * Long_Float'Truncation (Temp / M);
return Gen.Seed / M;
end Random;
---------------------------------------------------------------------------
function Get_Seed (Gen : in Generator) return Long_Float is
begin
return Gen.Seed;
end Get_Seed;
end Park_Miller_Time;
-------------------------------------------------------------------------------
-- Demonstration: Time-Based Seeding for Park-Miller RNG
--
-- Andrew J. Pounds, Ph.D.
-- Departments of Chemistry and Computer Science
-- Mercer University
-------------------------------------------------------------------------------
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Calendar;
with Ada.Calendar.Formatting;
with Park_Miller_Time; use Park_Miller_Time;
procedure Random_Time_Demo is
Gen : Generator;
R : Long_Float;
begin
Put_Line ("==============================================");
Put_Line (" Park-Miller RNG: Time-Based Seeding");
Put_Line (" Ada Implementation");
Put_Line ("==============================================");
New_Line;
-- Display current time
Put ("Current time: ");
Put_Line (Ada.Calendar.Formatting.Image (Ada.Calendar.Clock));
New_Line;
-- Method 1: Calendar-based seed
Put_Line ("Method 1: Seed from Ada.Calendar.Clock");
Put_Line ("----------------------------------------------");
Initialize_From_Calendar (Gen);
Put ("Generated seed: ");
Put (Get_Seed (Gen), Fore => 12, Aft => 1, Exp => 0);
New_Line (2);
Put_Line ("Random numbers:");
for I in 1 .. 5 loop
R := Random (Gen);
Put (" Random #");
Put (I, Width => 2);
Put (": ");
Put (R, Fore => 1, Aft => 10, Exp => 0);
New_Line;
end loop;
New_Line;
-- Method 2: Real_Time-based seed (higher resolution)
Put_Line ("Method 2: Seed from Ada.Real_Time.Clock");
Put_Line ("----------------------------------------------");
Initialize_From_Real_Time (Gen);
Put ("Generated seed: ");
Put (Get_Seed (Gen), Fore => 12, Aft => 1, Exp => 0);
New_Line (2);
Put_Line ("Random numbers:");
for I in 1 .. 5 loop
R := Random (Gen);
Put (" Random #");
Put (I, Width => 2);
Put (": ");
Put (R, Fore => 1, Aft => 10, Exp => 0);
New_Line;
end loop;
Put_Line ("----------------------------------------------");
Put_Line ("Run again to see different sequences!");
end Random_Time_Demo;
gnatmake random_time_demo.adb./random_time_demo==============================================
Park-Miller RNG: Time-Based Seeding
Ada Implementation
==============================================
Current time: 2024-01-15 14:32:07.54
Method 1: Seed from Ada.Calendar.Clock
----------------------------------------------
Generated seed: 847291630.0
Random numbers:
Random # 1: 0.5847291630
Random # 2: 0.1293847562
Random # 3: 0.7562019384
Random # 4: 0.3019384756
Random # 5: 0.8475620193
Method 2: Seed from Ada.Real_Time.Clock
----------------------------------------------
Generated seed: 1293847562.0
Random numbers:
Random # 1: 0.2938475621
Random # 2: 0.8475620193
Random # 3: 0.3920193847
Random # 4: 0.9384756201
Random # 5: 0.4756201938
----------------------------------------------
Run again to see different sequences!
Note: Your output will differ based on the current time.
Using std::time module
SystemTime::now() β Wall-clock time since UNIX epoch
Instant::now() β Monotonic high-resolution time
duration_since() β Calculate elapsed duration
Rust's std::time module provides SystemTime for wall-clock time
and Instant for monotonic measurements. We use nanosecond precision for
maximum seed uniqueness.
//! =============================================================================
//! Park-Miller RNG with Time-Based Seeding
//! Rust Implementation
//!
//! Adapted from: Park, S.K. & Miller, K.W. (1988)
//! "Random Number Generators: Good Ones Are Hard to Find"
//! Communications of the ACM, Vol. 31, No. 10, pp. 1192-1201
//!
//! Implementation by Andrew J. Pounds, Ph.D.
//! Departments of Chemistry and Computer Science
//! Mercer University
//! =============================================================================
use std::time::{SystemTime, Instant, UNIX_EPOCH};
/// Algorithm constants
const A: f64 = 16807.0;
const M: f64 = 2147483647.0;
const MAX_SEED: u64 = 2147483646;
/// Park-Miller random number generator with time-based seeding support
pub struct ParkMillerRng {
seed: f64,
}
impl ParkMillerRng {
/// Create a new generator with an explicit seed
pub fn new(seed: f64) -> Self {
ParkMillerRng { seed }
}
/// Create a generator seeded from SystemTime (wall clock)
pub fn from_system_time() -> Self {
let duration = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
// Use nanoseconds for high resolution
let nanos = duration.as_nanos() as u64;
let seed = (nanos % MAX_SEED) + 1;
println!("SystemTime seed: {}", seed);
ParkMillerRng { seed: seed as f64 }
}
/// Create a generator seeded from Instant (monotonic clock)
/// Note: Instant has no absolute reference, so we use elapsed from program start
pub fn from_instant(start: Instant) -> Self {
let elapsed = start.elapsed();
let nanos = elapsed.as_nanos() as u64;
// Combine with a constant to get better distribution
let seed = ((nanos ^ 0xDEADBEEF) % MAX_SEED) + 1;
println!("Instant-based seed: {}", seed);
ParkMillerRng { seed: seed as f64 }
}
/// Create a generator with combined time sources (recommended)
pub fn from_combined_time() -> Self {
let system_time = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
let nanos = system_time.as_nanos() as u64;
let secs = system_time.as_secs();
// XOR different time components for better mixing
let combined = nanos ^ (secs.wrapping_mul(1_000_000_007));
let seed = (combined % MAX_SEED) + 1;
println!("Combined time seed: {}", seed);
ParkMillerRng { seed: seed as f64 }
}
/// Generate the next random number in range (0, 1)
pub fn next(&mut self) -> f64 {
let temp = A * self.seed;
self.seed = temp - M * (temp / M).trunc();
self.seed / M
}
/// Get current seed value
pub fn get_seed(&self) -> f64 {
self.seed
}
}
/// Format current time as a readable string
fn format_current_time() -> String {
let duration = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
let secs = duration.as_secs();
let millis = duration.subsec_millis();
// Simple formatting (for full date formatting, use chrono crate)
format!("Unix timestamp: {}.{:03}", secs, millis)
}
fn main() {
let program_start = Instant::now();
println!("==============================================");
println!(" Park-Miller RNG: Time-Based Seeding");
println!(" Rust Implementation");
println!("==============================================");
println!();
println!("Current time: {}", format_current_time());
println!();
// Method 1: SystemTime seed
println!("Method 1: Seed from SystemTime::now()");
println!("----------------------------------------------");
let mut rng1 = ParkMillerRng::from_system_time();
println!();
println!("Random numbers:");
for i in 1..=5 {
println!(" Random #{:2}: {:.10}", i, rng1.next());
}
println!();
// Method 2: Instant-based seed
println!("Method 2: Seed from Instant (elapsed time)");
println!("----------------------------------------------");
let mut rng2 = ParkMillerRng::from_instant(program_start);
println!();
println!("Random numbers:");
for i in 1..=5 {
println!(" Random #{:2}: {:.10}", i, rng2.next());
}
println!();
// Method 3: Combined time sources (recommended)
println!("Method 3: Combined time seed (recommended)");
println!("----------------------------------------------");
let mut rng3 = ParkMillerRng::from_combined_time();
println!();
println!("Random numbers:");
for i in 1..=5 {
println!(" Random #{:2}: {:.10}", i, rng3.next());
}
println!("----------------------------------------------");
println!("Run again to see different sequences!");
}
Option A: Using rustc directly
park_miller_time.rsrustc park_miller_time.rs -o park_miller_time./park_miller_timeOption B: Using Cargo
cargo new park_miller_time && cd park_miller_timesrc/main.rs with the code abovecargo run --release==============================================
Park-Miller RNG: Time-Based Seeding
Rust Implementation
==============================================
Current time: Unix timestamp: 1705329127.542
Method 1: Seed from SystemTime::now()
----------------------------------------------
SystemTime seed: 1847362951
Random numbers:
Random # 1: 0.4729185630
Random # 2: 0.8193746285
Random # 3: 0.1638472951
Random # 4: 0.5847291630
Random # 5: 0.9374628510
Method 2: Seed from Instant (elapsed time)
----------------------------------------------
Instant-based seed: 293847562
Random numbers:
Random # 1: 0.2938475621
Random # 2: 0.7384756210
Random # 3: 0.1847562103
Random # 4: 0.6291038475
Random # 5: 0.0756210384
Method 3: Combined time seed (recommended)
----------------------------------------------
Combined time seed: 1029384756
Random numbers:
Random # 1: 0.5293847562
Random # 2: 0.9738475621
Random # 3: 0.4184756210
Random # 4: 0.8629103847
Random # 5: 0.3075621038
----------------------------------------------
Run again to see different sequences!
Note: Your output will differ based on the current time.