gpt4 book ai didi

java - 如何保持每次运行的值(value)不变?

转载 作者:行者123 更新时间:2023-11-29 10:19:24 29 4
gpt4 key购买 nike

使用 java 我想在一个程序中生成一些随机值,然后在每次执行第二个程序时在其他程序中使用这些值。

这样做的目的是生成一次随机值,然后在以后每次运行程序时保持并保持它们不变。有可能吗?谢谢

最佳答案

当您退出程序时,您没有存储在文件中的任何内容都会丢失。

我怀疑您不需要像您想象的那样担心 IO。您应该能够在几毫秒内读取数百万个值。事实上,您应该能够在几分之一秒内生成数百万个随机数。

Random random = new Random(1);
long start = System.nanoTime();
int values = 1000000;
for (int i = 0; i < values; i++)
random.nextInt();
long time = System.nanoTime() - start;
System.out.printf("Took %.3f seconds to generate %,d values%n",
time / 1e9, values);

打印

Took 0.015 seconds to generate 1,000,000 values

生成和写入

int values = 1000000;
ByteBuffer buffer = ByteBuffer.allocateDirect(4 * values).order(ByteOrder.nativeOrder());

Random random = new Random(1);
long start = System.nanoTime();
for (int i = 0; i < values; i++)
buffer.putInt(random.nextInt());
buffer.flip();
FileOutputStream fos = new FileOutputStream("/tmp/random.ints");
fos.getChannel().write(buffer);
fos.close();
long time = System.nanoTime() - start;
System.out.printf("Took %.3f seconds to generate&write %,d values%n", time / 1e9, values);

打印

Took 0.021 seconds to generate&write 1,000,000 values

读取同一个文件。

long start2 = System.nanoTime();
FileInputStream fis = new FileInputStream("/tmp/random.ints");
MappedByteBuffer buffer2 = fis.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, values * 4).order(ByteOrder.nativeOrder());
for (int i = 0; i < values; i++)
buffer2.getInt();
fis.close();
long time2 = System.nanoTime() - start2;
System.out.printf("Took %.3f seconds to read %,d values%n", time2 / 1e9, values);

打印

Took 0.011 seconds to read 1,000,000 values

重复读取同一个文件

long sum = 0;
int repeats = 1000;
for (int j = 0; j < repeats; j++) {
buffer2.position(0);
for (int i = 0; i < values; i++)
sum += buffer2.getInt();
}
fis.close();
long time2 = System.nanoTime() - start2;
System.out.printf("Took %.3f seconds to read %,d values%n", time2 / 1e9, repeats * values);

打印

Took 1.833 seconds to read 1,000,000,000 values

关于java - 如何保持每次运行的值(value)不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9702464/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com