测试程序运行时间

程序本体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.example.util;

import java.time.LocalDateTime;

public class TimeUtil {

public interface Task {
void execute();
}

public static void check(String title, Task task) {
if (task == null) {
return;
}
title = (title == null) ? "" : ("[" + title + "]");
System.out.println(title);
System.out.println("开始:" + LocalDateTime.now());
long beginTime = System.currentTimeMillis();
task.execute();
long endTime = System.currentTimeMillis();
System.out.println("结束:" + LocalDateTime.now());
double delta = (endTime - beginTime) / 1000.0;
System.out.println("耗时:" + delta + "秒");
System.out.println("=========");

}
}

调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.example;

import com.example.util.TimeUtil;

public class Main {

public static void main(String[] args) {
TimeUtil.check("testAdd", new TimeUtil.Task() {
@Override
public void execute() {
long res = 0;
for (long i = 0; i < 1000000000; i ++) {
res += i;
}
System.out.println(res);
}
});
}
}

运行结果

Python直接用time库就行

1
2
3
4
5
6
7
8
import time

# 程序开始时的时间
time_start = time.time()
# 程序结束时系统时间
time_end = time.time()
# 两者相减
print('totally cost', time_end - time_start)
作者

Etsu

发布于

2022-12-29

更新于

2022-12-29

许可协议

评论