我想比较两种不同的奇数或偶数测试方法,我想测试哪个更快,所以我尝试使用clock()
函数和clock_t
变量。
似乎没什么用。我在网上搜索了很多,并根据我在stackoverflow上找到的答案修改了我的代码,但仍然没有。
这是我的代码:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<stdint.h>
clock_t startm, stopm;
#define START if ( (startm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define STOP if ( (stopm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define PRINTTIME printf( "%ju ticks used by the processor.", (uintmax_t)(stopm-startm));
#define COUNT 18446744073709551600
#define STEP COUNT/100
int timetest(void){
unsigned long long int i = 0, y =0 , x = 76546546545541; // x = a random big odd number
clock_t startTime,stopTime;
printf("\nstarting bitwise method :\n");
START;
for(i = 0 ; i < COUNT ; i++){
if(x&1) y=1;
}
STOP;
printf("\n");
PRINTTIME;
y=0;
printf("\nstarting mul-div method :\n");
START;
for(i = 0; i < COUNT ; i++){
if(((x/2)*2) != x ) y=1;
}
STOP;
printf("\n");
PRINTTIME;
printf("\n\n");
return 0;
}
我总是以0 ticks used by the processor.
作为输出。
任何帮助都将受到高度赞赏。
修改:
iv有足够的编译器问题。 创建了上述程序的java版本。给了我答案。虽然它适用于java平台。
public class test {
private final static int count = 500000000;
private final static long num = 55465465465465L;
private final static int loops = 25;
private long runTime;
private long result;
private long bitArr[] = new long[loops];
private long mulDivArr[] = new long[loops];
private double meanVal;
private void bitwiser() {
for (int i = 0; i < count; i++) {
result = num & 1;
}
}
private void muldiv() {
for (int i = 0; i < count; i++) {
result = (num / 2) * 2;
}
}
public test() {
// run loops and gather info
for (int i = 0; i < loops; i++) {
runTime = System.currentTimeMillis();
bitwiser();
runTime = System.currentTimeMillis() - runTime;
bitArr[i] = runTime;
runTime = System.currentTimeMillis();
muldiv();
runTime = System.currentTimeMillis() - runTime;
mulDivArr[i] = runTime;
}
// calculate stats
meanVal = stats.mean(bitArr);
System.out.println("bitwise time : " + meanVal);
meanVal = stats.mean(mulDivArr);
System.out.println("muldiv time : " + meanVal);
}
public static void main(String[] args) {
new test();
}
}
final class stats {
private stats() {
// empty
}
public static double mean(long[] a) {
if (a.length == 0)
return Double.NaN;
long sum = sum(a);
return (double) sum / a.length;
}
public static long sum(long[] a) {
long sum = 0L;
for (int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
}
输出(以毫秒为单位):
bitwise time : 1109.52
muldiv time : 1108.16
平均来说,按位似乎比muldiv慢一点。
答案 0 :(得分:4)
此:
#define COUNT 18446744073709551600
会溢出,您必须附加ULL
才能使文字具有unsigned long long
类型。