有没有一款软件/网站可以提交我的C、C++和Java代码,并获得程序执行时间、内存使用等统计信息?我想比较不同语言中相同代码的性能,并估算哪种数据结构/操作更适合哪种语言。
自己动手。在*nix机器(例如Linux和OSX)上,只需从终端运行:
time java YourJavaProgram
或者
time ./YourCProgram
time_before = get_now()
// do something
span = get_time() - time_before
可以通过java.lang.Runtime.getRuntime()在程序中获取程序的总使用/空闲内存。
运行时有几种与内存相关的方法。下面的代码示例演示了它的用法。
package test;
import java.util.ArrayList;
import java.util.List;
public class PerformanceTest {
private static final long MEGABYTE = 1024L * 1024L;
public static long bytesToMegabytes(long bytes) {
return bytes / MEGABYTE;
}
public static void main(String[] args) {
// I assume you will know how to create a object Person yourself...
List<Person> list = new ArrayList<Person>();
for (int i = 0; i <= 100000; i++) {
list.add(new Person("Jim", "Knopf"));
}
// Get the Java runtime
Runtime runtime = Runtime.getRuntime();
// Run the garbage collector
runtime.gc();
// Calculate the used memory
long memory = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Used memory is bytes: " + memory);
System.out.println("Used memory is megabytes: "
+ bytesToMegabytes(memory));
}
}
package performance.test;
class TimeTest1 {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long total = 0;
for (int i = 0; i < 10000000; i++) {
total += i;
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println(elapsedTime);
}
}
这被称为基准测试,你可以自己做。问题在于许多其他变量会影响结果,因此最好控制环境并测量程序的性能,尽可能消除外部变量。
例如,建议在相同的机器上进行所有程序的测量,并使用相同的环境,尽可能实现这一点。