Python:通過執行100萬次打印來比較C和python的性能,以及用C和python結合來解決性能問題的方法
python作為動態語言,開發效率相當高,但如我們所知,動態語言的執行效率往往是比較低的,請看下面簡單的測試過程:
一、 C語言實現100萬次打印:
代碼:
[cpp]
- #include<stdio.h>
- #include <time.h>
-
- int main(int argc, char* argv[])
- {
- unsigned long i = 1;
- unsigned long ulNum = 1000000;
-
- clock_t start, finish;
- double duration;
-
- start = clock();
-
- while (ulNum != 0)
- {
- printf("\nThe ulNum is: %u ", i);
- ulNum--;
- i++;
- }
-
- finish = clock();
- duration = (double)(finish - start) / CLOCKS_PER_SEC;
- printf( "\n Use Time: %f seconds\n", duration );
-
- system("pause");
-
- return 0;
- }
測試:
可看出,執行了約489秒。
二、python實現100萬次打印:
代碼:
[python]
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
-
- import time
- import os
-
- time_begin = time.clock()
-
- i = 1
- ulNum = 1000000
- while (ulNum != 0):
- print "The ulNum is: %u " % i
- ulNum -= 1
- i += 1
- print "Use time: %s" % (time.clock() - time_begin)
- os.system("pause")
測試:
可看出,執行了約675秒。