当前位置: 动力学知识库 > 问答 > 编程问答 >

c - calculation of wall clock

问题描述:

How to modify this code to do sequential

program to calculate the wall clock time

(time_t) needed to calculate the dot product

of the complex numbers.

#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");

}

}

网友答案:

A typical approach is to record time() twice and run the code many times to get a 1st order approximation.

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);

Suggest using profiling tools for a more accurate answer.


@Jonathan Leffler suggestion to use clock() is also an improvement.

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

Given 1) @Jonathan Leffler 2nd suggestion about the legitimacy of repeating since a compiler may out-think the code and 2) cache issues hints that any brute force methods as suggested here are at best illustrative and not definitive time measurements.

分享给朋友:
您可能感兴趣的文章:
随机阅读: