几周前我向Stackoverflow提出了一个问题,即创建一个有效的算法来搜索大块文本中的模式.现在我使用String函数indexOf进行搜索.一个建议是使用Rabin-Karp作为替代方案.我按如下方式编写了一个小测试程序来测试Rabin-Karp的实现,如下所示.
public static void main(String[] args) {
String test = "Mary had a little lamb whose fleece was white as snow";
String p = "was";
long start = Calendar.getInstance().getTimeInMillis();
for (int x = 0; x < 200000; x++)
test.indexOf(p);
long end = Calendar.getInstance().getTimeInMillis();
end = end -start;
System.out.println("Standard Java Time->"+end);
RabinKarp searcher = new RabinKarp("was");
start = Calendar.getInstance().getTimeInMillis();
for (int x = 0; x < 200000; x++)
searcher.search(test);
end = Calendar.getInstance().getTimeInMillis();
end = end -start;
System.out.println("Rabin Karp time->"+end);
}
Run Code Online (Sandbox Code Playgroud)
以下是我正在使用的Rabin-Karp的实现: …
我想测试某些代码块的运行时间如下:
start = System.currentTimeMillis();
{
...
this.dosomething();
}
end = System.currentTimeMillis();
System.out.println(end - start);
Run Code Online (Sandbox Code Playgroud)
当我优化代码块时,如何快速注释那些快速计算时间的代码?
//start = System.currentTimeMillis();
{
...
this.dosomething();
}
//end = System.currentTimeMillis();
//System.out.println(end - start);
Run Code Online (Sandbox Code Playgroud) 我想知道是否java.util.Random.next(n)与n线性比例或是一个常数吗?有人可以帮我这个或者告诉我如何确定复杂性?
我正在尝试用java创建基准测试.目前我有以下简单的方法:
public static long runTest(int times){
long start = System.nanoTime();
String str = "str";
for(int i=0; i<times; i++){
str = "str"+i;
}
return System.nanoTime()-start;
}
Run Code Online (Sandbox Code Playgroud)
我目前在另一个多次发生的循环中多次进行此循环,并获得运行此方法所需的最小/最大/平均时间.然后我在另一个线程上开始一些活动并再次测试.基本上我只想获得一致的结果......如果我有一千万次runTest循环,它似乎非常一致:
Number of times ran: 5
The max time was: 1231419504 (102.85% of the average)
The min time was: 1177508466 (98.35% of the average)
The average time was: 1197291937
The difference between the max and min is: 4.58%
Activated thread activity.
Number of times ran: 5
The max time was: 3872724739 (100.82% of the average) …Run Code Online (Sandbox Code Playgroud) 我知道Java使用线性同余生成器.我的问题是 - 生成随机数的复杂性是多少?你如何进行这样的分析?
这可能是适合所有编程语言的问题(我想!).我在Groovy中有这样的代码:
def a =['asd','sdf','sdr','asd','tty','gfdg','dfgt','rfgsf','rfas','asddre','asdfr','adsrf']
start = System.currentTimeMillis()
println a.sort()
end = System.currentTimeMillis()
println "Sort in-built is ${end-start}"
def InsertionSort(def b = [])
{
for(out=1;out<b.size();out++)
{
temp = b[out]
in1 = out;
while(in1>0 && b[in1-1]>=temp)
{
b[in1] = b[in1-1]
--in1
}
b[in1] = temp;
}
return b
}
start = System.currentTimeMillis()
c = InsertionSort(a)
end = System.currentTimeMillis()
println "Insertion Sort is ${end-start}"
println c
Run Code Online (Sandbox Code Playgroud)
显然,上面的代码检查内置sort函数的运行时间和我的函数名称,InsertionSort该函数也执行相同的工作sort.
现在我在不同的时间运行相同的代码.说当我在8:34:33 pm执行代码时,我得到输出为:
[adsrf, asd, asd, asddre, asdfr, dfgt, …Run Code Online (Sandbox Code Playgroud) java ×6
algorithm ×2
annotations ×1
benchmarking ×1
c# ×1
debugging ×1
groovy ×1
rabin-karp ×1
random ×1
search ×1
sorting ×1
string ×1