2014-02-10 84 views
0

如何修改此代碼做序列 程序來計算複雜數字的點積 所需的掛鐘時間 (time_t)。牆上時鐘的計算

#include "stdafx.h" 
#include <stdlib.h> 
#include<stdio.h> 

typedef struct complex{ 
double real; 
double img; 
}complex; 

complex add(complex a, complex b); 
complex multiply(complex *a, complex *b); 


int _tmain(int argc, _TCHAR* argv[]) 
{ 
int choice, temp1, temp2; 
complex a, b, c; 

while (1) 
{ 
    printf("Press 1 to add two complex numbers.\n"); 
    printf("Press 2 to multiply two complex numbers.\n"); 
    printf("Press 3 to exit.\n"); 
    printf("Enter your choice\n"); 
    scanf_s("%d", &choice); 

    if (choice == 3) 
     exit(0); 

    if (choice >= 1 && choice <= 2) 
    { 
     printf("Enter a and b where a + ib is the first complex number."); 
     printf("\na = "); 
     scanf_s("%d", &a.real); 
     printf("b = "); 
     scanf_s("%d", &a.img); 
     printf("Enter c and d where c + id is the second complex number."); 
     printf("\nc = "); 
     scanf_s("%d", &b.real); 
     printf("d = "); 
     scanf_s("%d", &b.img); 
    } 
    if (choice == 1) 
    { 
     c.real = a.real + b.real; 
     c.img = a.img + b.img; 

     if (c.img >= 0) 
     printf("Sum of two complex numbers = %d + %di", c.real, c.img); 
     else 
     printf("Sum of two complex numbers = %d %di", c.real, c.img); 
    } 

    else if (choice == 2) 
    { 
     c.real = a.real*b.real - a.img*b.img; 
     c.img = a.img*b.real + a.real*b.img; 

    if (c.img >= 0) 
    printf("Multiplication of two complex numbers = %d + %di", c.real, c.img); 
     else 
    printf("Multiplication of two complex numbers = %d %di", c.real, c.img); 
    } 


    else 
    printf("Invalid choice."); 

    printf("\nPress any key to enter choice again...\n"); 
} 
    } 
+1

基準比較棘手。複雜的算術不是那麼複雜,你可以用'time_t'來測量它需要多長時間,在大多數系統上粒度爲1秒。您將不得不重複計算幾百萬次以使其花費足夠長的時間才能被測量,並且您可能需要使用比time()和time_t更好的度量。至少,使用'clock()'。更可能使用報告爲微秒的'gettimeofday()'或報告爲納秒的'clock_gettime()'。你在哪個平臺上? Windows的答案是不同的。 –

+1

請注意,如果優化程序發現您未使用計算結果,則可能會優化代碼中的計算,因此您將看到運行速度非常快。在不完全抑制優化器的情況下取消優化也是使基準測試變得困難的原因之一。 –

+0

@JonathanLeffler你[不應該使用'gettimeofday'](http://blog.eitanadler.com/2012/11/dont-use-gettimeofday2-or-time3-for.html)要麼(應該有另一個鏈接更有用的替代品,但我現在找不到它)。 – Kninnug

回答

1

的典型方法是記錄time()兩次並運行代碼多次獲得第一級近似。

time_t t0,t1; 
time(&t0); 
int N = 1000000; 
for (int i=0; i< N; i++) { 
    DoCodeUnderTest(); 
    // c.real = a.real + b.real; 
    // c.img = a.img + b.img; 
} 
time(&t1); 
printf("Time %e\n", (double) (t1-t0)/N); 

建議使用性能分析工具獲得更準確的答案。


@Jonathan Leffler建議使用clock()也是一種改進。

clock_t c1,c12; 
c1 = clock(); 
... // repeat runs of the code 
c2 = clock(); 
printf("Time %e\n", (double) (c1-c0)/CLOCKS_PER_SEC/N); 

鑑於1)@Jonathan萊弗勒約重複,因爲編譯器可以進行思考的代碼和2)高速緩存的問題暗示任何暴力方法如下建議正處於最好的說明,而不是最終的合法性第二個建議實時測量。