如何以毫秒为单位获得以C为单位的时间? (视窗)

前端之家收集整理的这篇文章主要介绍了如何以毫秒为单位获得以C为单位的时间? (视窗)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在网上搜索过但我只找到了一种方法,但是这样它就会以秒为单位而不是几毫秒.

我的代码是:

  1. #include <stdio.h>
  2. #include <assert.h>
  3. #include <time.h>
  4.  
  5. int main(void)
  6. {
  7. int solucion;
  8.  
  9. time_t start,stop;
  10. clock_t ticks;
  11. long count;
  12.  
  13. time(&start);
  14. solucion = divisores_it(92000000,2);
  15. time(&stop);
  16.  
  17. printf("Finnished in %f seconds. \n",difftime(stop,start));
  18. return 0;
  19. }

解决方法

跨平台的方式是使用ftime.

Windows特定链接http://msdn.microsoft.com/en-us/library/aa297926(v=vs.60).aspx

以下示例.

  1. #include <stdio.h>
  2. #include <sys\timeb.h>
  3.  
  4. int main()
  5. {
  6. struct timeb start,end;
  7. int diff;
  8. int i = 0;
  9. ftime(&start);
  10.  
  11. while(i++ < 999) {
  12. /* do something which takes some time */
  13. printf(".");
  14. }
  15.  
  16. ftime(&end);
  17. diff = (int) (1000.0 * (end.time - start.time)
  18. + (end.millitm - start.millitm));
  19.  
  20. printf("\nOperation took %u milliseconds\n",diff);
  21. return 0;
  22. }

我运行上面的代码并使用VS2008跟踪它,并看到它实际上调用了Windows GetSystemTimeAsFileTime函数.

无论如何,ftime会给你几毫秒的精度.

猜你在找的C&C++相关文章