In the following program, I want to measure the input time i.e. the time taken by user to enter the variables of the array :
#include <stdio.h>
#include <time.h>
int main()
{
int i, array[10];
double user_input_time;
clock_t input_start, input_end;
input_start = clock();
for (i = 0; i < 10; i++)
{
scanf("%d", &array[i]);
}
input_end = clock();
user_input_time = ((double)(input_end - input_start)) / CLOCKS_PER_SEC;
printf("User Input Time : %f\n", user_input_time);
return 0;
}
Above, what I'm getting is the processor time taken not the input time taken by user to enter all the 10 variable of the array.
Please, can someone help me in doing so.
Include: time.h
Use:
int main()
{
time_t start = time(NULL);
//Do your operations here
printf("%.2f\n", (double)(time(NULL) - start));
return 0;
}
Note - We can use clock_gettime for more precise results - link
Using clock_gettime
int main () {
struct timespec start, finish;
clock_gettime(CLOCK_REALTIME, &start);
// do your operations here
clock_gettime(CLOCK_REALTIME, &finish);
long seconds = finish.tv_sec - start.tv_sec;
long ns = finish.tv_nsec - start.tv_nsec;
if (start.tv_nsec > finish.tv_nsec) { // clock underflow
--seconds;
ns += 1000000000;
}
printf("seconds without ns: %ld\n", seconds);
printf("nanoseconds: %ld\n", ns);
printf("total seconds: %e\n", (double)seconds + (double)ns/(double)1000000000);
}
Which precision do you want ?
Because you can use simply time(NULL) if you only want to know the time at the second.
#include <stdio.h>
#include <time.h>
int main(void)
{
int i, array[10];
time_t user_input_time, input_start, input_end;
input_start = time(NULL);
for (i = 0; i < 10; i++)
{
scanf("%d", &array[i]);
}
input_end = time(NULL);
user_input_time = input_end - input_start;
printf("User Input Time : %d second\n", (int)user_input_time);
return 0;
}
You can use gettimeofday() from sys/time.h
#include <stdio.h>
#include <sys/time.h>
int main(void)
{
int i, array[10];
struct timeval input_start, input_end;
gettimeofday(&input_start, NULL);
for (i = 0; i < 10; i++)
{
scanf("%d", &array[i]);
}
gettimeofday(&input_end, NULL);
printf("User Input Time : %d second\n", input_end.tv_sec - input_start.tv_sec);
return 0;
}
Related
everybody!
I have two program estimating PI using Monte-Carlo technique : one using single-thread and one using multi-thread.
The single-thread one :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define BILLION 1000000000.0
int main(int argc, char *argv[])
{
struct timespec start, end;
///////////////////////
clock_gettime(CLOCK_REALTIME, &start);
///////////////////////
if(argc != 2)
{
fprintf(stderr, "usage: a.out <integer value>\n");
return -1;
}
if(atoi(argv[1]) < 0)
{
fprintf(stderr, "%d must be >= 0\n", atoi(argv[1]));
return -1;
}
time_t t;
srand((unsigned) time(&t));
int total = atoi(argv[1]);
int inside = 0;
unsigned int seed = rand()%30000;
for(int i = 0; i < total; ++i)
{
double rand_x = (double)rand_r(&seed)/(double)RAND_MAX;
double rand_y = (double)rand_r(&seed)/(double)RAND_MAX;
double dist = rand_x*rand_x + rand_y*rand_y;
if(dist < 1.0) ++inside;
}
double pi = (double)(4 * inside)/total;
clock_gettime(CLOCK_REALTIME, &end);
double time_spent = (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / BILLION;
printf("pi = %lf\n", pi);
printf("time = %f\n", time_spent);
return 0;
}
The multi-thread one:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <math.h>
#define N 5
#define BILLION 1000000000.0
int inside = 0;
pthread_mutex_t mutex;
void* countInside(void * n)
{
int total = (int)n;
int hit_count = 0;
unsigned int seed = rand()%30000;
for(int i = 0; i < total; ++i)
{
double rand_x = (double)rand_r(&seed)/(double)RAND_MAX;
double rand_y = (double)rand_r(&seed)/(double)RAND_MAX;
double dist = rand_x*rand_x + rand_y*rand_y;
if(dist < 1.0) ++hit_count;
}
pthread_mutex_lock(&mutex);
inside += hit_count;
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
struct timespec start, end;
///////////////////////
clock_gettime(CLOCK_REALTIME, &start);
///////////////////////
if(argc != 2)
{
fprintf(stderr, "usage: a.out <integer value>\n");
return -1;
}
if(atoi(argv[1]) < 0)
{
fprintf(stderr, "%d must be >= 0\n", atoi(argv[1]));
return -1;
}
int total = atoi(argv[1]);
srand((unsigned) time(NULL));
//int N;
//printf("Input the number of thread you desire : ");
//scanf("%d", &N);
int n = total/N;
//pthread_t* tid = malloc(sizeof(pthread_t) * (N));
pthread_t tid[N];
pthread_mutex_init(&mutex, NULL);
for(int i = 0; i < N; ++i)
{
pthread_create(&tid[i], 0, countInside, (void*)n);
}
for(int i = 0; i < N; ++i)
{
pthread_join(tid[i], NULL);
}
double pi = 4.0 * inside / total;
clock_gettime(CLOCK_REALTIME, &end);
double time_spent = (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / BILLION;
printf("pi = %lf\n", pi);
printf("time = %lf\n", time_spent);
return 0;
}
When i execute both program with 100000000 points, i get the ouput:
Ouput of single-thread:
quan#quan-VirtualBox:~/Documents/lab5$ ./pi_serial 100000000
pi = 3.141583
time = 1.576207
Output of multi-thread:
quan#quan-VirtualBox:~/Documents/lab5$ ./pi_multi-thread 100000000
pi = 3.141532
time = 1.446410
Note : There are sometimes multi-thread one is even slower than single-thread one.
What's the problem ? I thought multi-thread must have some speed-up compared to single-thread one. Is my multi-thread code wrong ? Please give me some advice? Thank you!
Im trying to count time of different for cycles inside my program but I can only do it for one at the same time.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <time.h>
#define SEED 35791246
main(int argc, char* argv)
{
int niter=20000;
int niter1=100000;
int niter2=1000000;
int niter3=10000000;
double x,y;
int i,count=0;
double z;
double pi;
clock_t begin = clock();
srand(SEED);
count=0;
for ( i=0; i<niter; i++) {
x = (double)rand()/RAND_MAX;
y = (double)rand()/RAND_MAX;
z = x*x+y*y;
if (z<=1) count++;
}
pi=(double)count/niter*4;
printf("Number of variables %d , Pi estimate: %g \n",niter,pi);
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Time Spent: %f seconds\n", time_spent);
srand(SEED);
count=0;
for ( i=0; i<niter1; i++) {
x = (double)rand()/RAND_MAX;
y = (double)rand()/RAND_MAX;
z = x*x+y*y;
if (z<=1) count++;
}
pi=(double)count/niter1*4;
printf("Number of variables %d , Pi estimate %g \n",niter1,pi);
}
When I try to add another "clock_t begin = clock();" for the second loop I get an error. How can I get time spent on each for cycle?
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define LIMIT 30000
void CreateArray(int *p, int N) {
int i;
p = (int *)malloc(N * sizeof(int));
srand((long)210);
for (i = 0; i < N; i++)
*(p + i) = rand() % LIMIT;
for (i = 0; i < N; i++)
printf("%d ", p[i]);
}
void Search(int *p, int N, int key) {
int comparisons = 0, success_search = 0;
int i;
clock_t start, end;
double elapsed;
start = clock();
for (i = 0; i < N; i++) {
if (key == p[i]) {
comparisons++;
success_search++;
printf("\nFound!");
break;
} else {
comparisons++;
printf("\nNot found!");
}
}
end = clock();
elapsed = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("\nTotal comparisons: %d \n", comparisons);
printf("Time elapsed: %f \n", elapsed);
printf("Successful comparisons: %d \n\n", success_search);
}
int main() {
int N, i, p, key;
key = 1;
CreateArray(&p, N = 7);
Search(&p, N, key);
}
I'm trying to create a pseudo-random array and then try to search for a specific number in it and keep track of the total comparisons made and the total time needed to complete the search. I have manually inserted a number that is not in the array and it keeps saying that the number was found after 3 comparisons. Also the time elapsed always appears to be zero. I can't figure out what's wrong.
Make the following changes.
1) You need to allocate array and pass it to different functions. So "n" should be a pointer.
int *n = NULL;
2) You want CreateArray() to allocate memory and pass the pointer.
void CreateArray (int **p, int N)
3) You have to pass pointer to Search(). So call from main() becomes
Search(p, N, key);
I think it should work fine as expected now.
For time elapsed, you refer to Weather Vane's comment in your question.
There are multiple problems in your code:
CreateArray should return the pointer to the allocated space. Passing it a pointer to a local int in main() makes no sense.
you should test for malloc potential failure.
Search should get the pointer to the allocated array, not the address of a local int.
Search should print the Not found message just once at the end of the scan phase.
If you want to count the number of successful comparisons, you should not break from the loop when you find the first one, but then the total number of comparisons is N.
for better timing accuracy, you should avoid using printf inside the timed fragment.
you should free the memory before exiting the program.
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define LIMIT 30000
void CreateArray(int N) {
int i;
int *p = (int *)malloc(N * sizeof(int));
if (p != NULL) {
srand((long)210);
for (i = 0; i < N; i++)
*(p + i) = rand() % LIMIT;
for (i = 0; i < N; i++)
printf("%d ", p[i]);
}
return p;
}
void Search(int *p, int N, int key) {
int comparisons = 0, success_search = 0;
int i;
clock_t start, end;
double elapsed;
start = clock();
for (i = 0; i < N; i++) {
comparisons++;
if (key == p[i])
success_search++;
}
end = clock();
elapsed = ((double)(end - start)) / CLOCKS_PER_SEC;
if (success_search)
printf("Found!\n");
else
printf("Not found!\n");
printf("Total comparisons: %d\n", comparisons);
printf("Successful comparisons: %d\n\n", success_search);
printf("Time elapsed: %f\n", elapsed);
}
int main() {
int N, i, key;
int *p;
key = 1;
N = 7;
p = CreateArray(N);
if (p == NULL) {
fprintf(stderr, "cannot allocate memory for %d elements\n", N);
return 1;
}
Search(p, N, key);
free(p);
return 0;
}
Could someone provide an OpenMP program where the speedup is visible compared to without it. I'm finding it extremely difficult to achieve speedup. Even this simple program runs slower with OpenMP. My processor is Intel® Core™ i3-2370M CPU # 2.40GHz × 4 running on Linux (Ubuntu 14.10)
#include <cmath>
#include <stdio.h>
#include <time.h>
int main() {
clock_t t;
t = clock();
const int size = 4;
long long int k;
#pragma omp parallel for num_threads(4)
for(int n=0; n<size; ++n) {
for(int j=0;j<100000000;j++){
}
printf("\n");
}
t = clock() - t;
printf ("It took me %d clicks (%f seconds).\n",t,((float)t)/CLOCKS_PER_SEC);
return 0;
}
I had a problem related to this, where I wanted to find the max value of an array. I made the same mistake as you, I used clock for measuring the elapsed time. To fix this, I used clock_gettime() instead, and now it works.
As for an example code where the speedup is measurable (Note you migth want to change the value of N):
#include <omp.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
struct timespec diff(struct timespec start, struct timespec end)
{
struct timespec temp;
if(end.tv_sec - start.tv_sec == 0)
{
temp.tv_nsec = end.tv_nsec - start.tv_nsec;
}
else
{
temp.tv_nsec = ((end.tv_sec - start.tv_sec)*1000000000) + end.tv_nsec - start.tv_nsec;
}
return temp;
}
int main()
{
unsigned int N;
struct timespec t_start, t_end;
clock_t start, end;
srand(time(NULL));
FILE *f = fopen("out.txt", "w");
if(f == NULL)
{
printf("Could not open output\n");
return -1;
}
for(N = 1000000; N < 100000000; N += 1000000)
{
fprintf(f, "%d\t", N);
int* array = (int*)malloc(sizeof(int)*N);
if(array == NULL)
{
printf("Not enough space\n");
return -1;
}
for(unsigned int i = 0; i<N; i++) array[i] = rand();
int max_val = 0.0;
clock_gettime(CLOCK_MONOTONIC, &t_start);
#pragma omp parallel for reduction(max:max_val)
for(unsigned int i=0; i<N; i++)
{
if(array[i] > max_val) max_val = array[i];
}
clock_gettime(CLOCK_MONOTONIC, &t_end);
fprintf(f, "%lf\t", (double)(diff(t_start, t_end).tv_nsec / 1000000000.0));
max_val = 0.0;
clock_gettime(CLOCK_MONOTONIC, &t_start);
for(unsigned int i = 0; i<N; i++)
{
if(array[i] > max_val) max_val = array[i];
}
clock_gettime(CLOCK_MONOTONIC, &t_end);
fprintf(f, "%lf\n", (double)(diff(t_start, t_end).tv_nsec / 1000000000.0));
free(array);
}
fclose(f);
return 0;
}
Calculating a integral is a classical one, adjust the parts constant to increase the execution time and see more clearly the runtime, more parts, more execution time. It's getting 21.3 seconds with OpenMP enabled and 26.7 seconds, on a SINGLE core, DUAL thread Intel pentium 4:
#include <math.h>
#include <stdio.h>
#include <omp.h>
#define from 0.0f
#define to 2.0f
#define parts 999999999
#define step ((to - from) / parts)
#define x (from + (step / 2.0f))
int main()
{
double integralSum = 0;
int i;
#pragma omp parallel for reduction(+:integralSum)
for (i = 1; i < (parts+1); ++i)
{
integralSum = integralSum + (step * fabs(pow((x + (step * i)),2) + 4));
}
printf("%f\n", integralSum);
return 0;
}
It calculates the definite integral from 0 to 2 of x^2 + 4
This question already has answers here:
Prime Number Algorithm
(7 answers)
Closed 8 years ago.
This is my code for finding 10000th prime number but it is really slow, it takes 7 seconds to calculate.
#include <stdio.h>
#include <stdlib.h>
long int prime (int n)
{
int i;
for(i=2;i<n;i++)
{
if(n%i==0)
return 0;
}
return 1;
}
int main()
{
int i=2,counter=0;
while(1)
{
if(prime(i))
counter++;
if(counter==10000)
break;
i++;
}
printf("10000th prime number is: %d",i);
}
It is brute force method so that's probably reason why it's so slow.
I think problem may be that it has to call function so many times. So what do you think can it be optimised or it's better to find some math formula for this.
You can reduce the time substantially by making the following changes to prime():
Stopping at sqrt(n).
Starting at i=3, and incrementing i by 2.
Here's a program that contains both versions and the time taken by each.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>
int is_prime1 (int n)
{
int i;
for(i=2;i<n;i++)
{
if(n%i==0)
return 0;
}
return 1;
}
void do_it1(int max)
{
clock_t start = clock();
clock_t end;
int i=2,counter=0;
while(1)
{
if(is_prime1(i))
counter++;
if(counter==max)
break;
i++;
}
end = clock();
printf("%dth prime number is: %d\n", max, i);
printf("Time taken: %lf\n", 1.0*(end-start)/CLOCKS_PER_SEC);
}
int is_prime2 (int n)
{
int i;
int stop = sqrt(n);
for(i=3;i<=stop;i+=2)
{
if(n%i==0)
return 0;
}
return 1;
}
void do_it2(int max)
{
clock_t start = clock();
clock_t end;
int i=3,counter=1;
while(1)
{
if(is_prime2(i))
counter++;
if(counter==max)
break;
i += 2;
}
end = clock();
printf("%dth prime number is: %d\n", max, i);
printf("Time taken: %lf\n", 1.0*(end-start)/CLOCKS_PER_SEC);
}
int main(int argc, char** argv)
{
int max = atoi(argv[1]);
do_it1(max);
do_it2(max);
}
Sample execution:
./test 10000
Sample output:
10000th prime number is: 104729
Time taken: 9.469000
10000th prime number is: 104729
Time taken: 0.078000
To optimized your code a little bit (changes are made based on comments):
long int prime (int n)
{
int i;
int e = (int)sqrt(n);
for(i=2; i<=e;i++)
{
if(n%i==0)
return 0;
}
return 1;
}
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int *prime;
int prime_n;
void make_prime_table(int n){
prime = malloc(sizeof(int) * n / 2);
prime_n =0;
prime[prime_n++] = 2;
prime[prime_n++] = 3;
int i, j;
for(i = 5; i <= n; i +=2){
bool is_prime = true;
for(j = 1; j < prime_n ; ++j){
int t = prime[j];
if(t * t > i)
break;
if(i % t == 0){
is_prime = false;
break;
}
}
if(is_prime)
prime[prime_n++] = i;
}
}
int main(void){
int n = 105000;
make_prime_table(n);
if(prime_n >= 10000)
printf("10000th prime number is: %d\n", prime[9999]);
free(prime);
return 0;
}