Find Prime Numbers using time.h in C

Click For Summary

Discussion Overview

The discussion revolves around timing algorithms for finding prime numbers in C, specifically comparing different methods of measuring execution time. Participants explore the use of the `time.h` library and other potential timing solutions, while also addressing issues in the provided code.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • One participant describes their algorithm for finding prime numbers and seeks advice on timing the execution accurately.
  • Another participant suggests using the `clock()` function for timing, but notes that it measures CPU time rather than elapsed time.
  • Some participants propose wrapping the code in a loop to measure longer execution times for better accuracy.
  • There is mention of using profiling tools for more precise timing measurements.
  • One participant points out that printing primes to the screen may consume more time than the prime-checking function itself.
  • Another participant shares a code snippet using `clock()` to measure time in milliseconds, highlighting its limitations.
  • One participant discusses using the `times()` function from `` as an alternative, noting its accuracy issues and providing an example of its implementation.

Areas of Agreement / Disagreement

Participants express differing views on the best method for timing execution, with no consensus on a single approach. There is acknowledgment of the limitations of the `clock()` function and the potential benefits of using profiling tools, but no agreement on a definitive solution.

Contextual Notes

Participants mention various limitations of timing methods, including the accuracy of the `clock()` function and the impact of outputting results to the screen on timing measurements.

Who May Find This Useful

This discussion may be useful for programmers and developers interested in optimizing algorithm performance and accurately measuring execution time in C, particularly in the context of computational tasks like finding prime numbers.

Kalouste
Messages
21
Reaction score
0
I've written an algorithm that has the following goal: finding all prime numbers up to a specified integer. I've made two different algorithms actually: on one hand, I've used the concept beyond the ancient sieve of eratosthenes; on the other, I've used a function called isprime() that tests if a number is prime. For instance, let's say I want to determine which method is faster. So I need to time a piece of code in each algorithm.

As an example, here's the code of the first algorithm:

Code:
#include <stdio.h>
#include <math.h>
#include <time.h>

int isprime(int num);

int main () {
int n, num;
time_t t1, t2;

printf("Enter a number\n");

while (scanf("%d", &n) != 1) {
printf("Error: Try again.\n");
	while (getchar() != '\n')
		;
		}

printf("Prime numbers\n");

time(&t1);

for (num = 2; num <= n; num += 1) {
if (isprime(num) == 1)
printf("%d\n", num);

}

time(&t2); 
printf("Time elapsed: %f ms\n", (float)(t2-t1));

return 0;
}

I've omitted the isprime() function definition, because I felt it's unnecessary. The problem with this approach is that my computer writes the numbers so rapidly that I probably will need to write the time in milliseconds if I wanted the algorithm to write every prime number up to a small number, as 11. Is there a function that allows me to do that?
Thank you on advance.

Links I've consulted

"[URL
 
Last edited by a moderator:
Technology news on Phys.org
There is the clock() function. But if you want really accurate timing, your best bet is to do one of the following: (I think (1) is the most reliable)

(1) Wrap your code in a loop and repeat it a few thousand times (or million, as necessary), so that the elapsed time is measured in seconds or minutes.

(2) Use a profiling tool.

(3) Try and find an API for the high-performance timer provided by your operating system.



Incidentally, there are two problems with your code:
(1) Printing the primes to screen is probably more time-consuming than the calls to isprime().

(2) On the final printf(...) call, you told it to print an int value (%d), but passed it a float.
 
Note though that the clock() function measures the cpu time not the elapsed time.
 
(2) On the final printf(...) call, you told it to print an int value (%d), but passed it a float.
Sorry for that, didn't notice.

About the clock() function I will try to use it. I found an interesting thread about that function http://www.thescripts.com/forum/thread213478.html" . When I come up with a fully functional solution I will post it. The (3) solution will also be considered. I didn't know about the existence of 'profiling tools', so I just learned something. Thank you for the suggestions.
 
Last edited by a moderator:
you have figured out by now, if not maybe this can help

Code:
#include <ctime>

clock_t cstart = clock();
...
clock_t cend = clock();

double millis = 1000.0 * (cend - cstart) / CLOCKS_PER_SEC;
 
The clock() function returns, as MeJennifer stated before, the cpu time which is less than the elapsed time (recall Hurkyl's post: 'Printing the primes to screen is probably more time-consuming than the calls to isprime()'). So I tried this solution, which seems to work although it's not extremely accurate, as one could desire (nor is the clock() function: it returns 0.00000 s cpu time if the computation is done too fast):

Code:
#include <sys/times.h>
#include <sys/wait.h>

  static clock_t st_time;
  static clock_t en_time;
  static struct tms st_cpu;
  static struct tms en_cpu;

  st_time = times(&st_cpu);
  ...
  en_time = times(&en_cpu);

printf("Time elapsed: %ld ms\n", (en_time - st_time));

Example: Print all primes up to 200.
Cpu_time: 0.000000 s
Time elapsed: 0 s (using <time.h>)
Time elapsed: 15 ms (using struct)

http://www.codeproject.com/csharp/highperformancetimercshar.asp"
 
Last edited by a moderator:

Similar threads

  • · Replies 28 ·
Replies
28
Views
5K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
7
Views
2K
  • · Replies 36 ·
2
Replies
36
Views
2K
  • · Replies 22 ·
Replies
22
Views
4K
Replies
14
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 9 ·
Replies
9
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K