java - 以纳秒为单位衡量程序的运行时间

标签 java algorithm encryption timer aes

在测试各种加密文件大小时,我应该测量下面代码的运行时间。但是我认为我使用的方法只是输出CPU的当前定时器而不是程序的运行时间。这是要实现的代码,但我认为我没有做对

long startTime = System.nanoTime();

// call function
obj.callFunction();

long endTime = System.nanoTime();
long timeDifference = endTime - startTime;

这是我的实际程序。我应该如何修改计时器代码以反射(reflect)程序的实际运行时间而不是系统时钟?谢谢!

import javax.crypto.Cipher;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;


public class AESJava {

    public static void main(String[] args) {


        // returns the current value of the system timer, in nanoseconds
          System.out.print("time in nanoseconds = ");
          System.out.println(System.nanoTime());


        try {



            BufferedReader br = new BufferedReader(new FileReader("key.txt"));
            String key = br.readLine();
            br.close();
            FileInputStream fis = new FileInputStream("original.txt");
            FileOutputStream fos = new FileOutputStream("encrypted.txt");
            encrypt(key, fis, fos);

            FileInputStream fis2 = new FileInputStream("encrypted.txt");
            FileOutputStream fos2 = new FileOutputStream("decrypted.txt");
            decrypt(key, fis2, fos2);

        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static void encrypt(String key, InputStream is, OutputStream os) throws Throwable {
        encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
    }

    public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable {
        encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
    }

    public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {


      SecretKeySpec dks = new SecretKeySpec(key.getBytes(),"AES");
        Cipher cipher = Cipher.getInstance("AES"); 

        if (mode == Cipher.ENCRYPT_MODE) {
            cipher.init(Cipher.ENCRYPT_MODE, dks);
            CipherInputStream cis = new CipherInputStream(is, cipher);
            doCopy(cis, os);        
        } else if (mode == Cipher.DECRYPT_MODE) {
            cipher.init(Cipher.DECRYPT_MODE, dks);
            CipherOutputStream cos = new CipherOutputStream(os, cipher);
            doCopy(is, cos);
        }


    }

    public static void doCopy(InputStream is, OutputStream os) throws IOException {
        byte[] bytes = new byte[128];
        int numBytes;
        while ((numBytes = is.read(bytes)) != -1) {
            os.write(bytes, 0, numBytes);
        }
        os.flush();
        os.close();
        is.close();
    }

}

最佳答案

我很困惑,因为你的第一件事是绝对正确的,但是你的主要方法并没有按照你写的去做。它只打印 CPU 时间(自纪元以来),不计算实际的挂钟时间。更改程序的最简单方法是创建一个方法(函数)来执行您的主要方法所做的事情,然后只需插入初始部分即可。以下是摘录:

private static void doMain(){
    try {
        BufferedReader br = new BufferedReader(new FileReader("key.txt"));
        String key = br.readLine();
        br.close();
        FileInputStream fis = new FileInputStream("original.txt");
        FileOutputStream fos = new FileOutputStream("encrypted.txt");
        encrypt(key, fis, fos);

        FileInputStream fis2 = new FileInputStream("encrypted.txt");
        FileOutputStream fos2 = new FileOutputStream("decrypted.txt");
        decrypt(key, fis2, fos2);

    } catch (Throwable e) {
        e.printStackTrace();
    }
}

那么您的主要方法就是:

public static void main(String ...args){
     long startTime = System.nanoTime();

     // call function
     doMain();

     long endTime = System.nanoTime();
     long timeDifference = endTime - startTime;
}

计算平均时间的更好方法是多次执行此操作(需要纳秒精度的单次运行不会非常准确)。所以你可以这样做:

public static void main(String ...args){
     long startTime = System.nanoTime();

     // call function
     for(int i = 0; i < NUM; ++i)
         doMain();

     long endTime = System.nanoTime();
     long timeDifference = endTime - startTime;
     double avgTime = (double)timeDifference / (double)NUM;
}

尽管这可能不准确,但我会强烈提醒您。在尝试计时时需要注意两件事:1) 操作系统是否会假设数据已经在 RAM 中,以及 2) 体系结构是否会假设数据已经在缓存中。如果你运行这么多次,你可能会以 RAM 的速度运行,而不是以读/写磁盘的速度运行。要真正获得平均速度,您需要确保操作系统必须读取/写入磁盘(这可能需要许多中间“虚拟”读取/写入)。

关于java - 以纳秒为单位衡量程序的运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22652351/

相关文章:

java - 减少列表中的重复元素

java - 如何使用 for 循环在 if 条件为 true 时始终将字符串更改为另一个字符串并更改为数组中的另一个

java - setUndecorated 不适用于非默认外观和感觉

c# - 生成具有少量唯一值的数据集

iphone - sqlcipher:无法访问提供十六进制 key 的数据库

java - 如何为对象添加或减去字符串值,并在值为空时将值设置为 "none"?

algorithm - 在恒定时间内插入到排序列表中

c - C 中的简单 AES 函数(不是库)?

python - 如何使用python读取加密文件夹

javascript - 密码散列(非 SSL)