fork(4) download
  1. #include <sys/time.h>
  2. #include <stdio.h>
  3.  
  4. double getdoubletime() {
  5. struct timeval t;
  6. gettimeofday(&t, NULL);
  7. return (double) t.tv_sec + ((double) t.tv_usec * 1e-6);
  8. }
  9.  
  10. #include <math.h>
  11. #include <stdlib.h>
  12.  
  13. #define N 65536
  14.  
  15. int main(int argc, char const *argv[]) {
  16. size_t i;
  17. double t0;
  18. // generate some random floating-point numbers
  19. double numbers[N];
  20. double fractionals[N];
  21. for (i=0; i<N; ++i) {
  22. numbers[i] = rand() + rand() / (double)RAND_MAX;
  23. }
  24. // extract fractional part: method 1
  25. t0 = getdoubletime();
  26. for (i=0; i<N; ++i) {
  27. fractionals[i] = remainder(numbers[i], 1.0);
  28. }
  29. printf("method 1 took %lf seconds (using remainder)\n", getdoubletime() - t0);
  30. // extract fractional part: method 2
  31. t0 = getdoubletime();
  32. for (i=0; i<N; ++i) {
  33. fractionals[i] = numbers[i] - (long)numbers[i];
  34. }
  35. printf("method 2 took %lf seconds (casting to long)\n", getdoubletime() - t0);
  36. // extract fractional part: method 3
  37. t0 = getdoubletime();
  38. for (i=0; i<N; ++i) {
  39. fractionals[i] = numbers[i] - floor(numbers[i]);
  40. }
  41. printf("method 3 took %lf seconds (using floor)\n", getdoubletime() - t0);
  42. // extract fractional part: method 4
  43. t0 = getdoubletime();
  44. double integral;
  45. for (i=0; i<N; ++i) {
  46. fractionals[i] = modf(numbers[i], &integral);
  47. }
  48. printf("method 4 took %lf seconds (using modf)\n", getdoubletime() - t0);
  49. // extract fractional part: method 5
  50. t0 = getdoubletime();
  51. for (i=0; i<N; ++i) {
  52. fractionals[i] = fmod(numbers[i], 1.0);
  53. }
  54. printf("method 5 took %lf seconds (using fmod)\n", getdoubletime() - t0);
  55.  
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0.01s 2544KB
stdin
Standard input is empty
stdout
method 1 took 0.003156 seconds (using remainder)
method 2 took 0.000000 seconds (casting to long)
method 3 took 0.000001 seconds (using floor)
method 4 took 0.001966 seconds (using modf)
method 5 took 0.003049 seconds (using fmod)